在ASP.net MVC 中, 當伺服器叫用自己web API 時, 有機會遇到cross-site scripting 問題. 有幾種解決方法.
- 建立新attribute 去應對. 自己加入HTTP header 好處是可以決定什麼web API call 可以CROS.
using System; using System.Web.Http.Filters; public class AllowCrossSiteAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response != null) { actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); } base.OnActionExecuted(actionExecutedContext); } }
叫用方法:
public class TestController : ApiController { [AllowCrossSite] public IEnumerable<object> get([FromUri] DateTime startDate, [FromUri] DateTime endDate) { ...
- 修改web.config. 好處是可以一次過實行而不用修改代碼.
<configuration> <system.webServer> <!-- Enable Cross-site Scripting. --> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> </system.webServer> <configuration>
Leave a Reply