共计 1525 个字符,预计需要花费 4 分钟才能阅读完成。
在 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);
}
本文永久更新链接地址 :http://www.linuxidc.com/Linux/2017-05/143790.htm
正文完
星哥说事-微信公众号