简体   繁体   English

Web API和WPF客户端

[英]Web API and WPF client

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. 然后我创建了一个WPF项目。 However, now which project should I reference in order access the WebAPI and the underlying models? 但是,现在我应该参考哪个项目来访问WebAPI和底层模型?

Use the HttpWebRequest class to make request to the Web API. 使用HttpWebRequest类向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). 下面是我用来向其他一些宁静服务请求的快速示例(该服务仅允许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. 还有一个名为“Microsoft ASP.NET Web API客户端库”的nuget包,可用于向WebAPI发出请求。 More on that package here( http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client ) 有关该软件包的更多信息( http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM