CORS 不工作 ASP.Net MVC5

CORS not working ASP.Net MVC5

我正在尝试阻止 cross-domain 使用 CORS 访问我的资源。我也尝试过 WebApi.Cors 和自定义 ActionFilter。但我仍然能够从不允许的域访问数据。

我的ActionFilter代码如下

public class AllowCrossSiteAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "https://example.com");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
            base.OnActionExecuting(filterContext);
        }
}

我的控制器

    [HttpGet]
    [AllowCrossSite]
    public ActionResult Index(string username)
    {
      //return json data
    }

这些 headers 出现在响应中 headers 但为什么请求没有阻止其他域,我做错了什么?请帮忙

添加响应 headers 实际上不会提供任何类型的安全性。常规 cors 实现仅添加那些响应 headers 以通知客户端已应用的 cors 规则。

服务器上的某些东西需要将您的 cors 规则与请求的 origin / method 等 headers 进行比较,如果不匹配则发回 4XX 响应匹配。

NuGet 包 Microsoft.AspNet.WebApi.Cors 允许您执行如下操作:

[EnableCors(origins: "https://example.com")]

如果您更喜欢自己的自定义实现,可以在 github 上查看此属性的源代码。这应该可以让您很好地了解需要做什么才能让 cors 手动工作。它比看起来更简单,真的。