【问题标题】:Calling Web Api service from a .NET 2.0 client从 .NET 2.0 客户端调用 Web Api 服务
【发布时间】:2013-07-03 05:17:16
【问题描述】:

是否可以从 .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 不兼容

有没有什么方法可以在不添加任何 dll 的情况下从 .NET 2.0 客户端调用 Web Api 方法?

【问题讨论】:

    标签: c# .net web-services asp.net-web-api .net-2.0


    【解决方案1】:

    是否可以从 .NET 2.0 客户端调用 Web Api 方法?

    当然可以。您绝对可以从任何符合 HTTP 的客户端调用它。客户端甚至可能不是 .NET。

    例如,在 .NET 2.0 中,您可以使用 WebClient 类:

    using (var client = new WebClient())
    {
        client.Headers[HttpRequestHeader.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
    }
    

    如果你想发布一些价值:

    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
    }
    

    【讨论】:

    • 是的,但最后我们需要将字节响应再次转换为字符串以显示正确的响应
    猜你喜欢
    • 2010-10-16
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 2014-09-04
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多