47

I am trying to create a web application which works with cross-origin requests (CORS) in MVC 5. I have tried everything without any result.

With an attribute

public class AllowCrossSiteJsonAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");

        base.OnActionExecuting(filterContext);
    }
}

With EnableCors attribute

 [EnableCors("*")]

Nothing works I'm starting to think that it is impossible

2

7 Answers 7

68

Add the configuration setting in your web.config file to set the value for Access-Control-Allow-Origin in customHeaders like this -

<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

You would like to visit this and this for more details and some other options.

Sign up to request clarification or add additional context in comments.

2 Comments

it is showing the result like this: "from origin '127.0.0.1:8787' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
In my case, I needed to set "Access-Control-Allow-Origin" with "*" as indicated in this answer, but.... I also needed to add this to my angularjs clientside $http call: headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
60

What I think is the most convenient is to create your own class like this :

enter image description here

with the following code in it :

using System;
using System.Web.Mvc;

public class AllowCrossSiteAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");

        base.OnActionExecuting(filterContext);
    }
}

After this it's let you use this decorator on a method or on the whole controller

enter image description here enter image description here

You should be able to see that in your response header after this procedure

enter image description here

Thank's to this response

2 Comments

You should also include filterContext.RequestContext.HttpContext.Response.AddHeader("Vary", "Origin");
but i got error as "EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection"
1

I think you have to add it into "OnAuthentication" step or add config into your web config. You can try my code :) it works

 public class AllowCrossSiteJsonAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        }

    }

Comments

1

I've had success using the OWIN CORS implementation (nuget Microsoft.Owin.Cors) to enable Cors for MVC Controllers and Owin middleware, in addition to ApiControllers. Microsoft.AspNet.WebApi.Cors (using config.EnableCors() and the [EnableCors] attribute) only seems to work with ApiControllers.

See http://benfoster.io/blog/aspnet-webapi-cors for sample code.

1 Comment

Best answer if you don't want to use the wildcard '*'.
1

You can also use below code to allow cross-origin request

public void ProcessRequest (HttpContext context)
        {
     context.Response.AddHeader("Access-Control-Allow-Origin" , "*");
}

2 Comments

Where does this code go?
inside global.asax file
-2

Enabling CORS in mvc 5(core) first need to add Microsoft.AspNetCore.Cors package to your project. Then configure startup.cs like this for all website

public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
     //Add Cors support to the service
     services.AddCors();

     var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy();

     policy.Headers.Add("*");    
     policy.Methods.Add("*");          
     policy.Origins.Add("*");
     policy.SupportsCredentials = true;

     services.ConfigureCors(x=>x.AddPolicy("AllPolicy", policy));

 }


 public void Configure(IApplicationBuilder app, IHostingEnvironment  env)
 {
     // Configure the HTTP request pipeline.

     app.UseStaticFiles();
     //Use the new policy globally
     app.UseCors("AllPolicy");
     // Add MVC to the request pipeline.
     app.UseMvc();
 }

and then also you can use like this

[EnableCors("AllPolicy")]

Details here

5 Comments

An error: EnableCors doesn't take origins parameter
which version of asp.net mvc you are using ?
ohh for 5 things are different, check out the link in my update
check update, I have added for mvc 5
This solution is for .net core mvc, not suitable for mvc 5 (.net framework)
-6

To enable cross-origin requests, add the [EnableCors] attribute to your Web API controller or controller method:

[EnableCors(origins: "http://systematixindia.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
   // Controller method`enter code here`s not shown...
}

Read More

3 Comments

Your solution is for Web Api, read the title of question! It doesn't work for MVC.
this code can be added for Global configuration public static class WebApiConfig { public static void Register(HttpConfiguration config) { // To do : Set at global place ex web.config EnableCorsAttribute corsConfig = new EnableCorsAttribute("", "", "GET,POST"); // Web API configuration and services config.EnableCors(corsConfig);
@OmarIsaid That class (WebAPIConfig.cs) is not there in MVC projects

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.