45

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

Petar Bechev
  • 587
  • 2
  • 5
  • 11

7 Answers7

64

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.

Yogi
  • 9,174
  • 2
  • 46
  • 61
  • 8
    it is showing the result like this: "from origin 'http://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." – Istiyak Jan 09 '19 at 10:00
  • 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'}` – sports Mar 17 '23 at 17:27
59

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

Community
  • 1
  • 1
Fitch
  • 1,084
  • 1
  • 11
  • 17
  • You should also include `filterContext.RequestContext.HttpContext.Response.AddHeader("Vary", "Origin");` – Ibraheem Apr 10 '18 at 14:09
  • but i got error as "EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection" – Ishara Samintha Nov 11 '19 at 09:44
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.

PointZeroTwo
  • 2,142
  • 1
  • 17
  • 15
0

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", "*");
        }

    }
Alex Nguyen
  • 1,032
  • 12
  • 27
0

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

public void ProcessRequest (HttpContext context)
        {
     context.Response.AddHeader("Access-Control-Allow-Origin" , "*");
}
Rakesh Chaudhari
  • 3,310
  • 1
  • 27
  • 25
-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

Mostafiz
  • 7,243
  • 3
  • 28
  • 42
-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

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
  • 37
    Your solution is for Web Api, read the title of question! It doesn't work for MVC. – daniil_ Feb 16 '18 at 16:46
  • 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); – Omar Isaid Dec 19 '18 at 08:14
  • 1
    @OmarIsaid That class (WebAPIConfig.cs) is not there in MVC projects – Kappacake Oct 23 '19 at 12:13