CORS in ASP .NET MVC5

后端 未结 1 1847
青春惊慌失措
青春惊慌失措 2020-12-01 00:45

I have a MVC project in which I have a couple of JSON controller methods I want to expose cross domain. Not the entire site, just these two methods.

I basically want

相关标签:
1条回答
  • 2020-12-01 01:12

    As described in here: Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

    You should just create an action filter and set the headers there. You can use this action filter on your action methods wherever you want.

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

    If you want to add multiple domains, you can't just set the header multiple times. In your action filter you will need to check if the requesting domain is from your list of domains and then set the header.

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var domains = new List<string> {"domain2.com", "domain1.com"};
    
            if (domains.Contains(filterContext.RequestContext.HttpContext.Request.UrlReferrer.Host))
            {
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            }
    
            base.OnActionExecuting(filterContext);
        }
    
    0 讨论(0)
提交回复
热议问题