本文介绍了调用从.NET 2.0客户端Web API服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能调用从.NET 2.0客户端的Web API方法?

参照莅临指导:http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

似乎某些DLL的客户端不被兼容.NET 2.0

有什么方法来调用从.NET 2.0客户端的Web API方法,不添加任何的dll?

解决方案

当然,它的可能。您可以从绝对任何HTTP兼容客户端调用它。客户端甚至可能不会.NET。

例如.NET 2.0中,你可以使用 Web客户端 类:

 使用(VAR的客户=新的Web客户端())
{
    client.Headers [Htt的prequestHeaders.Accept] =应用/ JSON;
    字符串结果= client.DownloadString(http://example.com/values​​);
    //现在使用JSON解析器来解析得到的字符串找回一些CLR对象
}
 

如果你想发布一些值:

 使用(VAR的客户=新的Web客户端())
{
    client.Headers [Htt的prequestHeader.ContentType] =应用/ JSON;
    client.Headers [Htt的prequestHeader.Accept] =应用/ JSON;
    VAR数据= Encoding.UTF8.GetBytes({\福\:\栏\});
    byte []的结果= client.UploadData(http://example.com/values​​,POST,数据);
    //现在使用JSON解析器来解析得到的字符串找回一些CLR对象
}
 

Is it possible to call a Web Api method from a .NET 2.0 client?

Referring to the guide here: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

Some of these dlls for the client doesn't seem to be compatible with .NET 2.0

Are there any ways to call a Web Api method from a .NET 2.0 client without adding any dlls?

解决方案

Of course that it's possible. You can call it from absolutely any HTTP compliant client. The client might not even be .NET.

For example in .NET 2.0 you could use the WebClient class:

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeaders.Accept] = "application/json";
    string result = client.DownloadString("http://example.com/values");
    // now use a JSON parser to parse the resulting string back to some CLR object
}

and if you wanted to POST some value:

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    client.Headers[HttpRequestHeader.Accept] = "application/json";
    var data = Encoding.UTF8.GetBytes("{\"foo\":\"bar\"}");
    byte[] result = client.UploadData("http://example.com/values", "POST", data);
    // now use a JSON parser to parse the resulting string back to some CLR object
}

这篇关于调用从.NET 2.0客户端Web API服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 20:02