Set Access-Control-Allow-Origin in Web API

If you access your web api methods from another domain using JQuery Ajax or GetJSON method then there you may see an error like
XMLHttpRequest cannot load (url). No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘(url)’ is therefore not allowed access.

You can just install CORS with package manager

Install-Package Microsoft.AspNet.WebApi.Cors

Follow this link http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Or create a own simple attribute like

  • Add a new class AllowCrossSiteJsonAttribute
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            {
                if (actionExecutedContext.Response != null)
                    actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    
                base.OnActionExecuted(actionExecutedContext);
            }
        }
    
  • For whole API Controller
    [AllowCrossSiteJson]
    public class UserAPIController : ApiController
    {
            // GET api/userapi
            public HttpResponseMessage Get()
            {
                  return uservar;
            }
    }
    
  • For a specific API Call
    public class UserAPIController : ApiController
    {
             // GET api/userapi
             [AllowCrossSiteJson]
             public HttpResponseMessage Get()
             {
                   return uservar;
             }
    }
    

that’s it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s