Cors请求和MVC5

时间:2016-05-13 18:24:46

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

所以我对控制器有一个看法......

[AllowAnonymous]
[Route("MyView")]
public ActionResult MyView()
{
    // first attempt at solving problem
    Response.AddHeader("Access-Control-Allow-Origin", "*");
    Response.AddHeader("Access-Control-Allow-Headers", "*");
    Response.AddHeader("Access-Control-Allow-Methods", "*");

    return PartialView();
}

我尝试添加此属性(第二次尝试)...

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

因为我正在使用owin初始化我的应用程序,我认为这可能有效(第3次尝试)......

app.Use((context, next) =>
{
    if (context.Request.Method == "OPTIONS")
    {
        context.Response.StatusCode = 200;
        context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "*" });
        context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "*" });
        return context.Response.WriteAsync("handled");
    }

    return next.Invoke();
}).UseStageMarker(PipelineStage.PreHandlerExecute);

问题在于,如果我直接通过将网址放入浏览器来请求它,我会得到正确的标题...

Access-Control-Allow-Headers:*
Access-Control-Allow-Methods:*
Access-Control-Allow-Origin:*

...转移到邮递员测试这个,当我发出一个OPTIONS调用同一个URL我在标题中得到这个...

Allow: OPTIONS, TRACE, GET, HEAD, POST

...那么如何让MVC正确响应OPTIONS http动词,以便我可以在网站域外使用此视图?

修改

值得注意的是,我已经环顾四周,发现了所有这些以及更多......

The requested resource does not support http method 'OPTIONS'.?

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Why does this jQuery AJAX PUT work in Chrome but not FF

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

...我也非常熟悉使用CORS并向WebAPI提出CORS请求,但出于某种原因,我似乎无法向MVC提出CORS请求而不会看到这样的&# 34;虚设"回复。

我认为我需要的是一种覆盖/替换MVC默认行为到这个基于HttpVerb的请求的方法,以允许我在远程站点中嵌入视图。

1 个答案:

答案 0 :(得分:3)

安装这两个nuget包:

Microsoft.AspNet.Cors
Microsoft.Owin.Cors

然后在Startup.cs Configuration函数中添加此行:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);

        app.UseCors(CorsOptions.AllowAll);
    }
}

在我的演示设置中,我正在从域http://example.local(Apache)向域http://localhost:6569/(IIS Express)发送帖子请求。

没有app.UseCors(CorsOptions.AllowAll);(注意控制台中的警告而没有CORS标题):

before setting up CORS

添加包并将行添加到Configuration方法后:

After setting up CORS

正如您在屏幕截图中看到的那样,access-control-allow-origin已按预期添加到响应标头/