Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Wednesday, 4 May 2016

How to Enable CORS in the ASP.NET Web API

Have you ever come across the following error:

Cross-origin Request Blocked. The same origin policy disallows reading the resource”.

Us to! It turns out, we get this error due to lack of CORS support while sharing resources. When we try to consume the Web API from origin A in a web application residing in origin B, we get the above error. To solve this error, we need to have a good understanding of CORS.

Although the purpose of this article is to learn the practical implementation of enabling CORS in the ASP.NET Web API, we will give a fair amount of weight to the theoretical concept also. CORS stands for Cross-Origin Resource-Sharing. For various security reasons user agents cannot share resources if they are not from the same origin. Various examples of user agents are browsers, HTML documents, scripts, and XMLHttpRequest.

Let us try to understand the concepts of Cross-Origin and Same-Origin. The concept of Origin was described by RF 6454. Two URLs would be called of the same origin, if they have:

  1. Scheme (http)

  2. Host(server)

  3. Port(8888)

The Origin consists of the Scheme, Host, and the Port number.

7217.picture_1_DJ

If two resources have the same combination of scheme, host, and port then they are considered of the same origin, else of the cross origin.  Let us consider the following two URI

http://abc.com:80 and http://xyz.com:8080 are not of the same origin since their host and port are not the same. For the security reason resource sharing between these two URL may be restricted. Let us try to understand CORS with the example of XMLHttpRequest. We use the XMLHttpRequest to perform the  HTTP operation on the server from the HTML document. There are two URLs used in the XMLHttpRequest:

  1. Requested URL or URL of the server

  2. URL of the document which initiated the request

If both URLs have the same scheme, host, and port then XMLHttpRequest object will perform the operation else it will block the HTTP operation for security reasons.

Both the server and the browser must have the support of the CORS. By default all recent browsers have CORS support, but as an API developer we need to enable support of CORS in the Web API.



CORS in ASP.NET Web API

Here we have created a very simple ASP.NET Web API which returns an array of classes as shown in the image below:

2818.picture_2_DJ

As you can see that Web API is running on port 8458.  Next we are trying to get the data in a JavaScript application which is running on the URI with the port 5901:

4087.picture_3_DJ

In the HTML document we are using an XMLHttpRequest object to make the HTTP call. As it is evident that URI of Web API (URI of the resource requested) and the HTML document (URL from which the request originated) are not the same hence XMLHttpRequest object is blocking the resource sharing since they are not of the same origin. Very likely in the browser we will get the exception as shown in the image below:

1348.picture_4_DJ

Let us dig further into the bug. In the browser, open the developer tool and the network tab. You will find Origin and Host in Request Header as shown in the image below. It is clear that both are not the same, and CORS is not allowed by the user agent XMLHttpRequest.

5141.picture_5_DJ

If you look at the Response Header there would be no information about Access-Control-Allow-Origin.0361.picture_6_DJ



Since the server does not send a response about which origin can access the resource in the header, XMLHttpRequest object blocks the resource sharing in the browser.  Let us go ahead and enable the CORS support for the Web API.

Enabling CORS in ASP.NET Web API

To enable CORS in ASP.NET Web API 2.0, first you need to add the Microsoft.AspNet.WebApi.Cors package to the project. Either you can choose the command prompt to install the package or NuGet manager to search and install as shown in the image below:

5148.picture_7_DJ

You can configure CORS support for the Web API at three levels:

  1. At the Global level

  2. At the Controller level

  3. At the Action level

To configure CORS support at the global level, first install the CORS package and then openWebApiConfig.cs file from App_Start folder.


var cors = new EnableCorsAttribute("http://localhost:5901", "*", "*");

config.EnableCors(cors);



After enabling CORS at the global level, again host the Web API and examine the request and response header. Also notice that in the Enable CORS attribute we have set the Origin URL to the URL of the JavaScript App.

The Web API server is adding an extra header Access-Control-Allow-Origin in the response header as shown in the image below. The URL in the Access-Control-Allow-Origin header in the response header and the URL in the Origin header in the request header must be same then only XMLHttpRequest will allow the CORS operations. In some cases the value of the  Access-Control-Allow-Orgin response header will be set to a wild card character*. This means the server allows CORS support for all the origins instead of a particular origin.6644.picture_8_DJ

We have enabled the CORS support on the server, so we should not get the exception and data should be fetched in the browser.

As we discussed earlier, in the ASP.NET Web API, CORS support can be enabled at three different levels:

  1. At the Action level

  2. At the Controller level

  3. At the Global level

Enable CORS at the Action level

CORS support can be enabled at the action level as shown in the listing below:
[EnableCors(origins: "http://localhost:5901", headers: "*", methods: "*")]

public HttpResponseMessage GetItem(int id)

{

// Code here

}



In the above code listing we have enabled CORS for the GetItem action. Also we are setting parameters to allow all the headers and support all the HTTP methods by setting value to star.



Enable CORS at the Controller level

CORS support can be enabled at the controller level as shown in the listing below:
[EnableCors(origins: "http://localhost:5901", headers: "*", methods: "*")]

public class ClassesController : ApiController

{



In the above code listing we have enabled CORS for the Classes Controller. We are also setting parameters to allow all the headers and support all the HTTP methods by setting value to star. We can exclude one of the actions from CORS support using the [DisableCors] attribute.



Enable CORS at the Global level

To configure CORS support at the global level, first install the CORS package and then open theWebApiConfig.cs file from App_Start folder.
var cors = new EnableCorsAttribute("http://localhost:5901", "*", "*");

config.EnableCors(cors);



If you set the attribute in more than one scope, the order of precedence is as follows:

1030.picture_9_DJ

Attributes of EnableCors

There are three attributes pass to EnableCors:

  1. Origins: You can set more than one origins value separated by commas.If you want any origin to make AJAX request to the API then set origin value to wild card value star.

  2. Request Headers: The Request header parameter specifies which Request headers are allowed. To allow any header set value to *

  3. HTTP Methods: The methods parameter specifies which HTTP methods are allowed to access the resource. To allow all methods, use the wildcard value “*”. Otherwise set comma separated method name to allow set of methods to access the resources.

Putting that all together, you can enable CORS for two origins, for all the headers, and then post and get operations as shown in the listing below:
[EnableCors(origins: "http://localhost:5901,http://localhost:8768", headers: "*", methods: "post,get")]

public class ClassesController : ApiController

{

 

Optionally you can also pass credentials to the Web API and create a custom policy, but I hope you found this post about the basics of CORS in the ASP.NET Web API. Have something to add? Share your comments below!

Monday, 11 April 2016

Difference between ASP.NET MVC and ASP.NET Web API

While developing your web application using MVC, many developers got confused when to use Web API, since MVC framework can also return JSON data by using JsonResult and can also handle simple AJAX requests. In previous article, I have explained the Difference between WCF and Web API and WCF REST and Web Service and when to use Web API over others services. In this article, you will learn when to use Web API with MVC.

Asp.Net Web API VS Asp.Net MVC



  1. Asp.Net MVC is used to create web applications that returns both views and data but Asp.Net Web API is used to create full blown HTTP services with easy and simple way that returns only data not view.

  2. Web API helps to build REST-ful services over the .NET Framework and it also support content-negotiation(it's about deciding the best response format data that could be acceptable by the client. it could be JSON,XML,ATOM or other formatted data), self hosting which are not in MVC.

  3. Web API also takes care of returning data in particular format like JSON,XML or any other based upon the Accept header in the request and you don't worry about that. MVC only return data in JSON format using JsonResult.

  4. In Web API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.

  5. Asp.Net Web API is new framework and part of the core ASP.NET framework. The model binding, filters, routing and others MVC features exist in Web API are different from MVC and exists in the new System.Web.Httpassembly. In MVC, these featues exist with in System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand alone service layer.

  6. You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML or any others format and building a full blown HTTP service. Typically, this will be called Web API self hosting.

  7. When you have mixed MVC and Web API controller and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since boths are different.

  8. Moreover, Web API is light weight architecture and except the web application it can also be used with smart phone apps.


What do you think?

I hope you have got when to use Web API over MVC and how it works. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Comparing Asp.Net Web API Routing and Asp.Net MVC Routing

As you know, Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. A URL pattern is matched against the routes patterns defined in the Route dictionary in an Order and the first match wins. This means the first route which successfully matches a controller, action, and action parameters defined in the URL will call into the specified controller and action.


Asp.Net MVC application and Asp.Net Web API must have at least one route defined in order to function. Hence, Visual Studio templates defined for MVC and Web API must have a default route. Now let's understand the difference between Asp.Net MVC and Asp.Net Web API.

Default Route Pattern


The default route pattern for a Web API Project is defined as follows-

  1. config.Routes.MapHttpRoute(

  2. name: "DefaultApi", //route name

  3. routeTemplate: "api/{controller}/{id}", //route pattern

  4. defaults: new { id = RouteParameter.Optional } //parameter default values

  5. );


The literal api at the beginning of the Web API route pattern, makes it distinct from the standard MVC route. This is not mandatory but it is a good convention to differ Web API route from MVC route.

In Web API route pattern {action} parameter is optional but you can include an {action} parameter. Also, the action methods defined on the controller must be have an HTTP action verb as a prefix to the method name in order to work. So, you can also define the route for Web API as follows-

  1. config.Routes.MapHttpRoute(

  2. name: "DefaultApi",//route name

  3. routeTemplate: "api/{controller}/{action}/{id}",//route pattern

  4. defaults: new { id = RouteParameter.Optional }//parameter default values

  5. );


The default route pattern for an Asp.Net MVC Project is defined as follows-

  1. routes.MapRoute(

  2. name: "Default", //route name

  3. url: "{controller}/{action}/{id}", //route pattern

  4. defaults: new

  5. {

  6. controller = "Home",

  7. action = "Index",

  8. id = UrlParameter.Optional

  9. } //parameter default values

  10. );


As you have seen there is no literal before at the beginning of the Asp.Net MVC route pattern but you can add if you wish.

Route Processing


In Web API route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request is selected. The Action methods defined in the API controller must either have the HTTP action verbs (GET, POST, PUT, DELETE) or have one of the HTTP action verbs as a prefix for the Actions methods name as given below-

  1. public class ValuesController : ApiController

  2. {

  3. // GET api/

  4. public IEnumerable Get()

  5. {

  6. return new string[] { "value1", "value2" };

  7. }


  8. // GET api//5

  9. public string Get(int id)

  10. {

  11. return "value";

  12. }


  13. // POST api/

  14. public void Post([FromBody]string value)

  15. {

  16. }


  17. // PUT api//5

  18. public void Put(int id, [FromBody]string value)

  19. {

  20. }


  21. // DELETE api//5

  22. public void Delete(int id)

  23. {

  24. }

  25. }


  26. // OR You can also defined above API Controller as Verb Prefix


  27. public class ValuesController : ApiController

  28. {

  29. // GET api/values

  30. public IEnumerable GetValues()

  31. {

  32. return new string[] { "value1", "value2" };

  33. }

  34. // GET api/values/5

  35. public string GetValues(int id)

  36. {

  37. return "value";

  38. }

  39. // POST api/values

  40. public void PostValues([FromBody]string value)

  41. {

  42. }

  43. // PUT api/values/5

  44. public void PutValues(int id, [FromBody]string value)

  45. {

  46. }

  47. // DELETE api/values/5

  48. public void DeleteValues(int id)

  49. {

  50. }

  51. }


In Asp.Net MVC route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request is selected. The Action methods defined in the MVC controller do not have HTTP action verbs as a prefix for the Actions methods but they have name like as normal method as shown below-

  1. public class HomeController : Controller

  2. {

  3. // GET: /Home/Index

  4. public ActionResult Index() //method - Index

  5. {

  6. // To Do:

  7. return View();

  8. }

  9.  

  10. // Post: /Home/Index

  11. [HttpPost]

  12. public ActionResult Index(LoginModel model, string id)

  13. {

  14. // To Do:

  15. return View();

  16. }

  17. }


In MVC, by default HTTP verb is GET for using others HTTP verbs you need defined as an attribute but in Web API you need to define as an method's name prefix.

Complex Parameter Processing


Unlike MVC, URLs in Web API cannot contain complex types. Complex types must be placed in the HTTP message body and there should be only one complex type in the body of an HTTP message.

Base Library


Web API controllers inherit from System.Web.Http.Controller, but MVC controllers inherit fromSystem.Web.Mvc.Controller. Both the library are different but acts in similar fashion.
What do you think?

I hope you will enjoy the tips while programming with Asp.Net MVC and Web API. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Difference between WCF and Web API and WCF REST and Web Service

The .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles over the internet which may describe to whom you should use. Now a days, you have a lot of choices to build HTTP services on .NET framework. In this article, I would like to share my opinion with you over Web Service, WCF and now Web API.


Web Service



  1. It is based on SOAP and return data in XML form.

  2. It support only HTTP protocol.

  3. It is not open source but can be consumed by any client that understands xml.

  4. It can be hosted only on IIS.

WCF



  1. It is also based on SOAP and return data in XML form.

  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.

  3. The main issue with WCF is, its tedious and extensive configuration.

  4. It is not open source but can be consumed by any client that understands xml.

  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest



  1. To use WCF as WCF Rest service you have to enable webHttpBindings.

  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.

  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files

  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified

  5. It support XML, JSON and ATOM data format.

Web API



  1. This is the new framework for building HTTP services with easy and simple way.

  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.

  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)

  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.

  5. It can be hosted with in the application or on IIS.

  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.

  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API



  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.

  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.

  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).

  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

What do you think?

I hope, you have got when to use WCF, Web API and Web Service. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Tuesday, 5 April 2016

Difference between WCF and Web API and WCF REST and Web Service

e .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles over the internet which may describe to whom you should use. Now a days, you have a lot of choices to build HTTP services on .NET framework. In this article, I would like to share my opinion with you over Web Service, WCF and now Web API.


Web Service



  1. It is based on SOAP and return data in XML form.

  2. It support only HTTP protocol.

  3. It is not open source but can be consumed by any client that understands xml.

  4. It can be hosted only on IIS.

WCF



  1. It is also based on SOAP and return data in XML form.

  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.

  3. The main issue with WCF is, its tedious and extensive configuration.

  4. It is not open source but can be consumed by any client that understands xml.

  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest



  1. To use WCF as WCF Rest service you have to enable webHttpBindings.

  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.

  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files

  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified

  5. It support XML, JSON and ATOM data format.

Web API



  1. This is the new framework for building HTTP services with easy and simple way.

  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.

  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)

  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.

  5. It can be hosted with in the application or on IIS.

  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.

  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API



  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.

  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.

  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).

  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

I hope, you have got when to use WCF, Web API and Web Service. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.