简体   繁体   English

CORS无法正常使用ASP.Net MVC5

[英]CORS not working ASP.Net MVC5

I am trying to block cross-domain access to my resources using CORS. 我正在尝试使用CORS阻止对我的资源的跨域访问。 I have tried WebApi.Cors and custom ActionFilter too. 我也尝试过WebApi.Cors和自定义ActionFilter But I am still able to access the data from not allowed domains. 但是我仍然能够从不允许的域访问数据。

My ActionFilter code is below 我的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);
        }
}

My Controller 我的控制器

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

These headers are present in the response headers but why the request is not blocking from other domains, what am I doing wrong? 这些标头出现在响应标头中,但是为什么请求没有被其他域阻止,我在做什么错呢? Please help 请帮忙

Adding the response headers will not actually provide any sort of security. 添加响应头实际上不会提供任何形式的安全性。 Regular cors implementations only add those response headers to inform the client about the cors rules that were applied. 常规的cors实现仅添加那些响应标头,以通知客户端有关已应用的cors规则。

Something on the server needs to compare your cors rules to the origin / method etc headers of the request, and then send back a 4XX response if they don't match up. 服务器上的某些内容需要将您的cors规则与请求的origin / method等标头进行比较,如果不匹配,则发送回4XX响应。

The NuGet package Microsoft.AspNet.WebApi.Cors allows you to do something like this: NuGet包Microsoft.AspNet.WebApi.Cors允许您执行以下操作:

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

If you prefer to do your own custom implementation, you can see the source code for this attribute on github . 如果您喜欢执行自己的自定义实现,则可以在github上查看此属性的源代码。 That should give you a fairly good idea of what you need to do to make cors work by hand. 这应该使您对手动操作cors所需执行的操作有一个很好的了解。 It's simpler than it looks, really. 实际上,它比看起来简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM