Jan 15, 2014

Cross Origin Resource Sharing

Cross-origin resource sharing (CORS) works by letting server indicate which origins are allowed to call them. When browser make a request to other domain it sends along an origin in the request header with the value of domain from where its coming from. If the server allows CORS, it will send response with header Access-Control-Allow-Origin which indicates if call is allowed. If this header is not present the the browser will not allow javascript to receive the response. In addition to the origin, CORS let server indicate which HTTP methods are allowed. CORS doesn’t prevent the call from being invoked on the server; rather, it prevents the calling JavaScript from receiving the results. 

Request Header
Origin:http://localhost:55724

Response Header
Access-Control-Allow-Origin: http://localhost:55724

Web API 2 supports CORS via NuGet package Microsoft.AspNet.WebApi.Cors. Here is how you can enable CORS for your api. This can done globally or at the controller level or at the action level.
 
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //var cors = new EnableCorsAttribute("*", "*", "GET");
            config.EnableCors();
    
    
  [EnableCors("http://localhost:55725", "*", "GET")]
  public class ProductController : ApiController

Preflight Requests
For some CORS requests, the browser sends an additional request, called a “preflight request”, before it sends the actual request for the resource. The pre-flight request uses the HTTP OPTIONS method. If the preflight request succeeds, the browser sends the actual request.

Jan 10, 2014

IHttpActionResult

This is new feature to WebApi 2.0 In many ways this is similar to action result in asp.net mvc. There are some build in action result like mvc controller has view result, json result etc. Web api has OkResult, NotFoundResult, ExceptionResult,UnauthorizedResult,BadRequestResult, ConflictResult,RedirectResult,InvalidModelStateResult.
 
  public IHttpActionResult GetDetails(string name)
        {
            Product product = _productService.GetProduct(name);
            if (product == null)
                return NotFound();
            return Ok(product);
        }
This simplifies unit test, for example if you are using request object to create http response object then you need to do setup to unit test controller.

Routing With Attribute


This allows routing with Attribute on any action. This works for both Api as well as mvc controller. You can have multiple route to an action. This can also be applied at the controller level

[Route("Api/Product/{name:alpha}/Reviews")]
[Route("Api/Product/{id:int:min(1)}/Reviews")]
        public HttpResponseMessage GetReviews(int id)

[RoutePrefix("Api/Product")] : This will apply to all the routes in the controller

Following configuration change need to happen to make attribute route work
public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{name}", new {name = RouteParameter.Optional});

Notice MapHttpAttributeRoutes is before default route, this give opportunity for attribute route to be applied before default route.

Web Api Help Page

Install-Package Microsoft.AspNet.WebApi.HelpPage -Version 5.0.0

This will add following to the package config
<package id="Microsoft.AspNet.WebApi.HelpPage" version="5.0.0" targetFramework="net45" />

This install will not add any new assembly to the reference, but this will add Area HelpPage, with controller,model and view which will provide help page.

Documentation:
Update Project Property, build tab to check Xml Documentation file.
Open Areas->HelpPage->AppStart->HelpPageConfig file and uncomment
config.SetDocumentationProvider
Make sure it refers the same xml documentation file


Now open .../Help url