Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 746
Ivan-Mark Debono Avatar asked Nov 14 '13 10:11

Ivan-Mark Debono


1 Answers

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)

like image 129
scheien Avatar answered Sep 24 '22 12:09

scheien