首页 > 代码库 > Asp.Net MVC 中实现跨域访问

Asp.Net MVC 中实现跨域访问

在ASP.Net webapi中可以使用  Microsoft.AspNet.WebApi.Cors  来实现:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }

但在MVC中不能使用这个,需要自定义一个类:

public class AllowCrossSiteJsonAttribute: ActionFilterAttribute
    {
        private string[] _domains;
        public AllowCrossSiteJsonAttribute(string domain)
        {
            _domains= new string[] { domain };
        }
        public AllowCrossSiteJsonAttribute(string[] domains)
        {
            _domains = domains;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var context = filterContext.RequestContext.HttpContext;
            var host = context.Request.UrlReferrer?.Host;
            if (host != null && _domains.Contains(host))
            {
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            }
            base.OnActionExecuting(filterContext);
        }
    }

在被访问的控制器上加上AllowCrossSiteJson:

[AllowCrossSiteJson("localhost")]
        public JsonResult Index()
        {
            var holidays = new List<Holiday>
            {
                new Holiday
                {
                    Title="2 Weeks in Rhodes",
                    Price=688,
                    ImgUrl="http://media.wiley.com/product_data/coverImage/84/04702927/0470292784.jpg"
                },
                new Holiday
                {
                    Title="1 Weeks in Barbados",
                    Price=320,
                    ImgUrl="http://media.wiley.com/product_data/coverImage/84/04702927/0470292784.jpg"
                }
            };
            return Json(holidays, JsonRequestBehavior.AllowGet);
        }

 

Asp.Net MVC 中实现跨域访问