2014-03-13 169 views
0

我對webAPi有點新,我想在Web API上實現CORS(跨源資源共享)。我指的是這個Microsoft link。他們安裝了一個Nuget包使用CORS在WEBAPI中的實現 - .net framework 4.0

PM> Install-Package Microsoft.AspNet.Cors -Version 5.0.0-rc1 -Pre 

但是,我使用.NET Framework 4.0,它不工作。之後我用這個Nuget命令:

Install-Package Microsoft.AspNet.WebApi -Version 4.0.20710 

但是它不包含CORS類。那麼,我們有沒有其他不同的方式來實現CORS?

回答

3

我用下面,對我工作正常(認爲不能確定「4.0客戶端配置文件」位):

public class CorsHandler : DelegatingHandler 
{ 
    private const string Origin = "Origin"; 
    private const string AccessControlRequestMethod = "Access-Control-Request-Method"; 
    private const string AccessControlRequestHeaders = "Access-Control-Request-Headers"; 
    private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin"; 
    private const string AccessControlAllowMethods = "Access-Control-Allow-Methods"; 
    private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers"; 

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
{ 
    bool isCorsRequest = request.Headers.Contains(Origin); 
    bool isPreflightRequest = request.Method == HttpMethod.Options; 
    if (isCorsRequest) 
     { 
      if (isPreflightRequest) 
      { 
       var response = new HttpResponseMessage(HttpStatusCode.OK); 
       response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); 

       string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault(); 
       if (accessControlRequestMethod != null) 
       { 
        response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod); 
       } 

       string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders)); 
       if (!string.IsNullOrEmpty(requestedHeaders)) 
       { 
        response.Headers.Add(AccessControlAllowHeaders, requestedHeaders); 
       } 

       var tcs = new TaskCompletionSource<HttpResponseMessage>(); 
       tcs.SetResult(response); 
       return tcs.Task; 
      } 

      return base.SendAsync(request, cancellationToken).ContinueWith(t => 
      { 
       HttpResponseMessage resp = t.Result; 
       resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); 
        return resp; 
       }); 
      } 
      return base.SendAsync(request, cancellationToken); 
     } 
    } 

請記住,在你進行註冊程序啓動(我在Global.asax中)

GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler()); 
+0

我面臨着與user3409920所述相同的問題。當我嘗試你的解決方案時,它在'if(isCorsRequest)'內部的'return base.SendAsync(...)'語句上拋出StackOverFlow異常。你有解決這個問題的想法嗎? –

+0

嘿,那裏,只嘗試使用上面的這些返回語句之一。正如你所看到的,第一個將Headers返回到一起,而另一個不會。讓我知道你的投入。乾杯 – felipekm

0

的CORS包是Web API 2需要.NET框架4.5和Visual Studio /快遞2014年

它不適用於網絡API 1(您使用的.NET支持4.0)

參照this thread

+0

如果你在這裏包含一些來自給定線程的重要信息會更好。 – niyasc