[ASP.net MVC] 處理CROS 問題

在ASP.net MVC 中, 當伺服器叫用自己web API 時, 有機會遇到cross-site scripting 問題. 有幾種解決方法.

  1. 建立新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) {
    ...
  2. 修改web.config. 好處是可以一次過實行而不用修改代碼.
    <configuration>
      <system.webServer>
          <!-- Enable Cross-site Scripting. -->
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>
    <configuration>

     

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.