winForm中如何实现网络请求WebAPI获取数据

winForm中如何实现网络请求WebAPI获取数据,第1张

使用HttpWebRequest类:

```C#

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/api/data")

request.Method = "GET"

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

{

using (StreamReader reader = new StreamReader(response.GetResponseStream()))

{

string json = reader.ReadToEnd()

// Do something with the json

}

}

```

2. 使用WebClient类:

```C#

using (WebClient wc = new WebClient())

{

string json = wc.DownloadString("http://example.com/api/data")

// Do something with the json

}

```

 转载 在使用Web Api的时候,有时候只想返回JSON;实现这一功能有多种方法,本文提供两种方式,一种传统的,一种作者认为是正确的方法。

 巧敏核 JSON in Web API – the formatter based approach

只支持JSON最普遍的做法是:首先清除其他所有的formatters,然后只保留JsonMediaTypeFormatter。

有了HttpConfiguration的实例,你将会很简单的清除所有formatters,然后重新添加JsonMediaTypeFormatter。

实现代码如下:

configuration.Formatters.Clear()

configuration.Formatters.Add(new JsonMediaTypeFormatter())这种方式虽然可以实现功能,但是所有的conent negotiation还是会发生,这就会产生以下额外的开销了。因为,你已经知道要返回的结果了,也只想返回Json,其他的content negotiation都不需要了。

下面的方法可以很好的解决这个问题。

JSON in Web API – the conneg based approach

最好的方法是使用自定义的只返回Json Result的content negotiation代替Web Api中默认的content negotiation。

Conneg通过实现IContentNegotiator的Negotiator方法实现孝掘扩展。Negotiator方法返回ContentNegotiationResult(它包装了你选择的headers和formatter)。

下面的方法通过传递一个JsonMediaTypeFormatter给自定义的conneg negotiator,让它一直返回applicaton/json 的content-type以及JsonMediaTypeFormatter。这种方法避免了每次请求都要重新创建一次formatter。

代码如下:

public class JsonContentNegotiator : IContentNegotiator

{

private readonly JsonMediaTypeFormatter _jsonFormatter

public JsonContentNegotiator(JsonMediaTypeFormatter formatter)

{

_jsonFormatter = formatter

}

 拿稿 public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter>formatters)

{

var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"))

return result

}

}接下来,你需要在HttpConfiguration实例上注册你的新的实现机制:

var jsonFormatter = new JsonMediaTypeFormatter()

//optional: set serializer settings here

config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter))

通过替换默认的DefaultContentNegotiator,我们使用我们自定义的JsonContentNegotiator,它只支持Json,而且可以马上返回。

如果你想更深入的了解Content Negotiation的知识,你可以查看作者的这篇文章。

总结

通过使用自定义的JsonContentNegotiator替换系统默认的DefaultContentNegotiator,很好的实现Web Api只返回Json的功能,而且没有额外的开销。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12211127.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存