Web API 和 WPF 客户端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19975768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Web API and WPF client
提问by Ivan-Mark Debono
I've followed the following article to set up a simple Web API solution: http://www.codeproject.com/Articles/350488/A-simple-POC-using-ASP-NET-Web-API-Entity-Framewor
我按照以下文章设置了一个简单的 Web API 解决方案:http: //www.codeproject.com/Articles/350488/A-simple-POC-using-ASP-NET-Web-API-Entity-Framewor
I've omitted the Common project, Log4Net and Castle Windsor to keep the project as simple as possible.
为了使项目尽可能简单,我省略了 Common 项目、Log4Net 和 Castle Windsor。
Then I created a WPF project. However, now which project should I reference in order access the WebAPI and the underlying models?
然后我创建了一个 WPF 项目。但是,现在我应该参考哪个项目来访问 WebAPI 和底层模型?
回答by scheien
Use the HttpWebRequest class to make request to the Web API. Below a quick sample for something I've used to make requests to some other restful service (that service only allowed POST/GET, and not DELETE/PUT).
使用 HttpWebRequest 类向 Web API 发出请求。下面是我用来向其他一些安静服务发出请求的快速示例(该服务只允许 POST/GET,而不是 DELETE/PUT)。
HttpWebRequest request = WebRequest.Create(actionUrl) as HttpWebRequest;
request.ContentType = "application/json";
if (postData.Length > 0)
{
request.Method = "POST"; // we have some post data, act as post request.
// write post data to request stream, and dispose streamwriter afterwards.
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
writer.Close();
}
}
else
{
request.Method = "GET"; // no post data, act as get request.
request.ContentLength = 0;
}
string responseData = string.Empty;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseData = reader.ReadToEnd();
reader.Close();
}
response.Close();
}
return responseData;
There are also a nuget package available called "Microsoft ASP.NET Web API client libraries" which can be used to make requests to the WebAPI. More on that package here(http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client)
还有一个名为“Microsoft ASP.NET Web API 客户端库”的 nuget 包,可用于向 WebAPI 发出请求。有关该软件包的更多信息(http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client)

