简体   繁体   中英

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

I've omitted the Common project, Log4Net and Castle Windsor to keep the project as simple as possible.

Then I created a WPF project. However, now which project should I reference in order access the WebAPI and the underlying models?

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 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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