How do I use ASP.NET 5 WebAPI from WPF client

2k views Asked by At

I have an existing WPF client, and I am building new standalone WebServices using ASP.NET 5 WebAPI. I want to expose some metadata, like WebApiProxy or .wsdl/Mex, so I can auto generate a Proxy class in my WPF client.

2

There are 2 answers

0
Hardik On

You don't need create Proxy classes like Legacy Web Services instead you can directly access Web API using Endpoints/Url of your Web Api (as you configured it's route in WebApiConfig.cs class) To Access those Endpoints you can use HttpClient object , you dont need to configured in your client application

5
jpgrassi On

You don't need to create proxy's in your WPF client to communicate with your WEB API. In a simplest scenario, just use an HTTP Client to call your Web API endpoint:

Something like this would do:

// This should come from a factory or something. 
// Try to reuse as much as possible the HttpClient instance
var client = new HttpClient();

//Api Base address
client.BaseAddress = new Uri("http://localhost:9000/");

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//Sending a GET request to endpoint api/products/1
HttpResponseMessage response = await client.GetAsync("api/person/1");
if (response.IsSuccessStatusCode)
{
    //Getting the result and mapping to a Product object
    Person person = await response.Content.ReadAsAsync<Person>();
}

Edit: I'm editing the original answer because I wrote it using the HtppClient around a using statement which is very bad. To avoid people copy 'n pasting this into their solution and helping to propagate bad software out there I decided to modify it.