[ASP.NET MVC]利用Attribute的方式設定每個controller的action是否接受CORS

  • 336
  • 0
  • 2019-01-10

[ASP.NET MVC]利用Attribute的方式設定每個controller的action是否接受CORS

利用Attribute的方式,就可以動態設定看你要哪一個controller允許接受cors:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyProject.Filters
{
    public class AllowCrossOriginRequestAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string SSO_Accepted_DomainName = System.Configuration.ConfigurationManager.AppSettings["SSO_Accepted_DomainName"];
            if(string.IsNullOrEmpty(SSO_Accepted_DomainName))
            {
                SSO_Accepted_DomainName = "*";
            }
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", SSO_Accepted_DomainName);
            base.OnActionExecuting(filterContext);
        }
    }
}


Controller裡面只要這樣使用就可以了:

[AllowCrossOriginRequest]
public ActionResult YourMethod()
{
    return Json("Any content.....");
}



參考資料:
Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method
https://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method