Skip to content

Latest commit

 

History

History
109 lines (85 loc) · 4.83 KB

3. ASP.NET Web API.md

File metadata and controls

109 lines (85 loc) · 4.83 KB

ASP.NET Web API

In 2012, Microsoft released the first version of the ASP.NET Web API framework, which was designed to create RESTful web services.

Currently, this is Windows only. However, Microsoft is working on the next version, with the codename "ASP.NET vNext". This version will unify all ASP.NET technologies (Web Forms, MVC, Web API) into a single codebase, which will be cross-platform. This version is hosted on Github.

Architecture

Similar to ASP.NET MVC, a Web API uses a Controller to specify methods which map to URLs. However, the base class is different, i.e. we must derive our controllers from ApiController (either directly or indirectly). (Sidenote: in vNext there will be a single base class for MVC and Web API controllers).

A controller called ValuesController will by default map to the URL "api/values" (however, see later about [routing](4. Web API Routing.md)). Then, if it has a function with a name which starts with "Get" (example: Get(), GetValues() etc.), then it is assumed that the given function should handle a GET request for "api/values". Similarly, if there are other functions which start with Post, Put or Delete, they will handle the corresponding HTTP verbs to the given URL.

Inside a function in an API controller, we can then use whatever tool we like to read and/or write data, such as LINQ, Entity Framework or some other ORM tool Object-relational mapping (see later).

We can also specify explicitly that a function will handle GET/POST/PUT/DELETE requests by decorating them with the appropriate attribute:

public class MyController : ApiController
{
    [HttpGet]
    public List<CourseGrade> Grades()
    {
    	...
    }
    
    [HttpPost]
    public CourseGrade AddGrade(/* Probably some parameters... */)
    {
    }
    
    [HttpPut]
    public void UpdateGrade(/ *Some parameters... */)
    {
    }
}

JSON or XML?

In ASP.NET MVC, it is possible to create a method which returns JSON data explicitly. However, REST is not tied to any one type of formatting, and a Web Service is by no means required to return JSON data. Fortunately, the Web API framework takes care of this for us. Assume we've got a POCO class:

public class CourseGrade
{
    public int   CourseID { get; set; }
    public float Grade    { get; set; }
}

and a corresponding Web API method which returns a list of grades:

public class MyController : ApiController
{
    public List<CourseGrade> GetGrades()
    {
      // TODO: load the grades for the currently logged in user, and return them!
    }
}

As you will notice, the method is defined to return just a simple list of the CourseGrade class. There is nowhere any mention of either JSON nor XML. What happens behind the scenes is that the Web API framework will examine the "Accept" HTTP header, which will contain the MIME type which the client requests. This will usually contain either "application/xml" or "application/json". The framework will then use a corresponding serializer, based on this.

Note that the Web API framework has built-in support for these two formats, but we can easily add support for other formats as well: CSV, iCal, plain text etc.

CORS

An ASP.NET Web API will by default allow incoming requests from code originating from the same server as the API. It is however highly likely that other code will need to call our API, for instance if we were to create an App which would connect to our API.

In that case, we should use CORS (Cross-Origin Resource Sharing), which allows code from other domains to access our API. This is implemented by adding the "Access-Control-Allow-Origin" HTTP header to a response, with either a list of domains allowed to call the service, or a wildcard star in case anyone can use it. Clients will then check this by issuing a HTTP OPTIONS request before an actual request is issued, and if it allows them to make the request, they will.

How CORS works

A library which handles all the negotiations for us is available for ASP.NET Web API, it is available to Web API project via NuGet, and requires us to add the following two lines of code to the WebApiConfig.Register() function:

    // Assuming we allow access from anywhere:
	var cors = new EnableCorsAttribute("*", "*", "*");
	config.EnableCors(cors);

The parameters for the EnableCorsAttribute constructor are origin, header and methods respectively. For more details on how to setup and configure CORS check out this tutorial.