Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c# - Calling Web Api service from a .NET 2.0 client

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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);
    string resultContent = Encoding.UTF8.GetString(result, 0, result.Length);        

// now use a JSON parser to parse the resulting string back to some CLR object }


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...