Skip to main content

How to enable Cross-Origin Requests in ASP.NET Web API 2



According to Msdn, Cross-origin resource sharing (CORS) is a World Wide Web Consortium (W3C) specification (commonly considered part of HTML5) that lets JavaScript overcome the same-origin policy security restriction imposed by browsers. The same-origin policy means that your JavaScript can only make AJAX calls back to the same origin of the containing Web page (where “origin” is defined as he combination of hostname, protocol and port number). CORS relaxes this restriction by letting servers indicate which origins are allowed to call them. CORS is enforced by browsers but must be implemented on the server, and the most recent release of ASP.NET Web API 2 has full CORS support. With Web API 2, you can configure policy to allow JavaScript clients from a different origin to access your APIs.

CORS can be enabled using a Web API or OWIN Middleware. The one you choose to use will depend largely on your requirements.
In this article, we will be implementing CORS using the OWIN Middleware. To enable CORS for your entire application add the CORS middleware to your request pipeline using the UseCors extension method.
app.UseCors(CorsOptions.AllowAll)

A policy that will allows all headers, all methods, any origin and supports credentials
To gain good control, you will have to provide your own CorsPolicy:
public override void Register()
{
   var _policy = new CorsPolicy
   {
       AllowAnyMethod = true,
       AllowAnyHeader = true,

   };

   var source = ConfigurationManager.AppSettings[Constants.CorsOriginsSettingKey];

   if (source != null)
   {
       foreach (var source in origins.Split(';'))
       {
           _policy.Origins.Add(source);
       }
   }
   else
   {
       _policy.AllowAnyOrigin = true;
   }

   var _corsOptions = new CorsOptions
   {
       _corsPolicyProvider = new CorsPolicyProvider
       {
        _corsPolicyProvider = context => Task.FromResult(corsPolicy)
       }
   };

   app.UseCors(_corsOptions);
}

Summary
CORS framework in Web API is extensible such that supporting a dynamic list of origins is easy.

Comments

Popular posts from this blog

How to implement RESTful API Versioning in ASP.NET Web API 2 using IHttpRouteConstraint

The only thing constant in life is change, and that is proved everyday in our industry, API’s are cool to extend the functionality of your application and expose it to other developers. The cool thing about IT and software, it’s that things changes quite rapidly and so it’s the technology, hence technology can change and the needs of your organisation can change, hence in order to keep serving this evolving needs and keep been relevant, your api might need to change also. Small changes can be accommodated within the initial version, but changes that will risked breaking the existing code, will required the need for versioning.

Implementing a custom IHttpRouteConstraint

According to msdn, a IHttpRouteConstraint simply Represents a base class route constraint. What then is a route constraint? A route constraint simply gets or sets a dictionary of expressions that specify valid values for a URL parameter.

publicclassApiVersionRouteConstraint : IHttpRouteConstraint
  {

publicApiVersionRouteCo…

How to implement multi-tenancy with subdomains using Route Constraint in ASP.NET MVC

According to Wikipedia, The term "software multitenancy" refers to a software architecture in which a single instance of software runs on a server and serves multiple tenants. A tenant is a group of users who share a common access with specific privileges to the software instance. With a multitenant architecture, a software application is designed to provide every tenant a dedicated share of the instance - including its data, configuration, user management, tenant individual functionality and non-functional properties. Multitenancy contrasts with multi-instance architectures, where separate software instances operate on behalf of different tenants. By giving companies, access to a tenant through a subdomain of choice, will help to personalise the experience more and gives a sense of ownership to each tenant. This will go along way to bring consistency in there branding.
Implementing Route Constraint
You use route constraints to restrict the browser requests that match a partic…

How Wrong Use of Data Structure is Costing You Performance

Data structure is a specialise way of storing and organising data so that it can be access efficiently. Today a good chunk of our codes makes use of data structure, and the importance of using the proper data structure for the right job cannot be over emphasised. There are many types of data structure, each one designed to handle the storing and manipulation of data in a specific way. The trick here now is, knowing how to use data structure is not enough but knowing the type to use that’s suits your operation without sacrificing performance.  The determinant factor of the right data structure to use in your program is dependent on some factor like the type of operation you want to perform on the data set like Searching, addition, deletion and access by index.

Comparison between Basic Data Structures

Data Structure Addition Search Deletion Access by Index Array(T[]) O(N) O(N) O(N) O(1) LinkedList(LinkedList<T>) O(1)