Saturday, November 17, 2012

MVC4 Web API Starter needs to know

I have just tried to use the MVC 4 Web API. There are some findings that needs to know during the process,

1. Use cUrl command line tool to test out the rest end points

2. Modify the IIS or IIS Express settings to enable verb PUT, DELETE
This is a link to show how to do this.

3. If need to use web API provided HttpClient class
In package manager console, run:
    Install-Package Microsoft.AspNet.WebApi.Client projectname
to install the necessary libraries


4. This will be a quick example to return the result.

By Calling add MediaTypeWithQualityHeaderValue("application/xml"), a xml format data will be returned. By default, web api return Json format data.

use new System.Net.Http.HttpClient() to send Form data
To use xml format data, need to add the MediaTypeHeader
clt.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
To get the result
 var result = clt.GetAsync(new Uri("http://localhost:52094/api/videos")).Result
 
For post complex type data, Call PostAsJsonAsync() such as
clt.PostAsJsonAsync("http://localhost:52094/api/videos/222", customer).Result
 

5. There are some old examples to use HttpRequestMessage and its extension method CreateContent, which are deprecated. it is much easier now.

6. In debug->immediate window, enter GlobalConfiguration object to check the current formatters.
GlobalConfiguration.Configuration.Formatters

Count = 4

[0]: {System.Net.Http.Formatting.JsonMediaTypeFormatter}

[1]: {System.Net.Http.Formatting.XmlMediaTypeFormatter}

[2]: {System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter}

[3]: {System.Web.Http.ModelBinding.JQueryMvcFormUrlEncodedFormatter}
 
 


 

No comments: