如何在ASP.NET MVC中启用跨域请求

45

我试图创建一个能够处理跨域请求(CORS)的MVC 5网络应用程序,但是一直没有结果。

使用属性

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

        base.OnActionExecuting(filterContext);
    }
}

使用EnableCors属性

 [EnableCors("*")]

什么都不起作用,我开始觉得这是不可能的。


1
你读过这些示例吗:https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api - Sami Kuhmonen
我在这篇帖子中找到了解决方案:https://forums.asp.net/post/5795304.aspx - mejiamanuel57
7个回答

66
在你的web.config文件中添加配置设置,以在customHeaders中设置Access-Control-Allow-Origin的值,就像这样 -
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

您希望访问这个链接这个链接以获取更多细节和其他选项。


8
显示的结果如下:"由于 CORS 策略,原始来源 'http://127.0.0.1:8787' 被阻止:预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。" - Istiyak
在我的情况下,我需要按照这个答案中所示设置“Access-Control-Allow-Origin”为“*”,但是......我还需要将其添加到我的AngularJS客户端的$http调用中:headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'} - sports

60
我认为最方便的方法是创建自己的类,像这样:

输入图像描述

在其中加入以下代码:

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);
    }
}

在这之后,你可以将此装饰器用于一个方法或整个控制器

输入图片说明 输入图片说明

在完成此过程后,你应该能够看到它在你的响应头

输入图片说明

感谢这个回答


你还应该包含 filterContext.RequestContext.HttpContext.Response.AddHeader("Vary", "Origin"); - Ibraheem
但是我收到了一个错误,提示“EventSource的响应MIME类型为(“application/json”),而不是“text/event-stream”。连接已中止。” - Ishara Samintha

1
我已成功使用OWIN CORS实现(nuget Microsoft.Owin.Cors)来为MVC控制器和Owin中间件启用Cors,除了ApiControllers。Microsoft.AspNet.WebApi.Cors(使用config.EnableCors()[EnableCors]属性)似乎只适用于ApiControllers。
请参见http://benfoster.io/blog/aspnet-webapi-cors以获取示例代码。

1
如果您不想使用通配符“*”,最佳答案是:不要使用它。 - Flo

0

你也可以使用以下代码允许跨域请求

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

这段代码放在哪里? - Captain Kenpachi
全局.asax文件内部 - Rakesh Chaudhari

0

我认为你需要将它添加到“OnAuthentication”步骤中或者将配置添加到你的Web配置文件中。你可以尝试我的代码 :) 它有效。

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

    }

-2

在 MVC 5(核心)中启用 CORS 首先需要将 Microsoft.AspNetCore.Cors 包添加到您的项目中。然后为所有网站配置 startup.cs,如下所示:

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();
 }

然后你也可以像这样使用

[EnableCors("AllPolicy")]

详细信息在这里


一个错误:EnableCors不接受origins参数。 - Petar Bechev
你正在使用哪个版本的ASP.NET MVC? - Mostafiz
哦,有5件事情不同,请查看我的更新链接。 - Mostafiz
检查更新,我已经添加了MVC 5的内容。 - Mostafiz
此解决方案适用于 .net core mvc,不适用于 mvc 5 (.net framework)。 - Anh Hoang

-6

为了启用跨来源请求,请在您的Web API控制器或控制器方法中添加[EnableCors]属性:

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

阅读更多


37
你的解决方案适用于Web API,读一下问题标题就知道了!它不适用于MVC。 - daniil_
这段代码可以添加到全局配置中:public static class WebApiConfig { public static void Register(HttpConfiguration config) { // 在全局位置设置,如 web.config EnableCorsAttribute corsConfig = new EnableCorsAttribute("*", "*", "GET,POST"); // Web API 配置和服务 config.EnableCors(corsConfig); - Omar Isaid
1
@OmarIsaid,MVC项目中没有WebAPIConfig.cs这个类。 - Kappacake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接