【问题标题】:How to enable cross origin requests in ASP.NET MVC [duplicate]如何在 ASP.NET MVC 中启用跨源请求 [重复]
【发布时间】:2017-02-26 00:19:59
【问题描述】:

我正在尝试创建一个适用于 MVC 5 中的跨域请求 (CORS) 的 Web 应用程序。我已经尝试了所有方法,但没有任何结果。

带有属性

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

        base.OnActionExecuting(filterContext);
    }
}

带有 EnableCors 属性

 [EnableCors("*")]

没有任何效果我开始认为这是不可能的

【问题讨论】:

标签: c# asp.net asp.net-mvc cors


【解决方案1】:

在您的 web.config 文件中添加配置设置,以像这样在 customHeaders 中设置 Access-Control-Allow-Origin 的值 -

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

您想访问thisthis 了解更多详情和其他一些选项。

【讨论】:

  • 它显示的结果如下:“来自原点 '127.0.0.1:8787' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。”
【解决方案2】:

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

其中包含以下代码:

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

在此之后,您可以在方法或整个控制器

上使用此装饰器

在此过程之后,您应该能够在 响应标题 中看到它

感谢response

【讨论】:

  • 您还应该包括filterContext.RequestContext.HttpContext.Response.AddHeader("Vary", "Origin");
  • 但我收到错误,因为“EventSource 的响应具有不是“文本/事件流”的 MIME 类型(“应用程序/json”)。中止连接“
【解决方案3】:

我已经成功使用 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

【讨论】:

  • 如果您不想使用通配符“*”的最佳答案。
【解决方案4】:

我认为您必须将其添加到“OnAuthentication”步骤或将配置添加到您的网络配置中。你可以试试我的代码 :) 它有效

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

    }

【讨论】:

    【解决方案5】:

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

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

    【讨论】:

    • 这段代码去哪儿了?
    • 在 global.asax 文件中
    【解决方案6】:

    在 mvc 5(core) 中启用 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")]
    

    详情here

    【讨论】:

    • 一个错误:EnableCors 没有使用 origins 参数
    • 您使用的是哪个版本的 asp.net mvc?
    • 哦,有 5 件事不同,请查看我的更新中的链接
    • 检查更新,我已经为 mvc 5 添加了
    • 此方案适用于.net core mvc,不适用于mvc 5(.net framework)
    【解决方案7】:

    要启用跨域请求,请将[EnableCors] 属性添加到您的 Web API 控制器或控制器方法中:

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

    Read More

    【讨论】:

    • 您的解决方案是针对Web Api的,请阅读问题标题!它不适用于 MVC。
    • 可以为全局配置添加此代码 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 配置和服务 config.EnableCors(corsConfig);
    • @OmarIsaid 该类 (WebAPIConfig.cs) 在 MVC 项目中不存在
    猜你喜欢
    • 2015-05-19
    • 2017-10-10
    • 2015-07-05
    • 2015-10-29
    • 2016-11-23
    • 2017-03-26
    • 2017-07-27
    • 2016-08-12
    • 1970-01-01
    相关资源
    最近更新 更多