2017-06-22 68 views
1

我已經在Web API上啓用了COR並且在Chrome上,GET和POST請求都失敗了,但在MS Edge瀏覽器中,GET請求沒有問題,但是當我嘗試POST請求時,在控制檯中出現兩條錯誤消息失敗:CORs在Web API 2.0上的請求

由於無效的 語法,服務器無法處理該請求。

XMLHttpRequest:網絡錯誤0x80070005,訪問被拒絕。

後的代碼是一個標準的Ajax請求與跨域啓用:

$.ajax({ 
    type: "POST", 
    crossDomain: true, 
    url: 'http://localhost:50915/api/addjob', 
    data: JSON.stringify(Job), 
    contentType: "application/json;charset=utf-8", 
    success: function (data, status, xhr) { 
     alert("The result is : " + status + ": " + data); 
    }, 
    error: function (xhr) { 
     alert(xhr.responseText); 
    } 
}); 

而且在Web API方面我已經安裝了CORS NuGet包,並增加了以下啓用代碼:

WebApiConfig.cs

public static void Register(HttpConfiguration config) 
     { 
      // Web API configuration and services 
      config.EnableCors(); 

      // Web API routes 
      config.MapHttpAttributeRoutes(); 

      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 

      var JsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault(); 
      if (JsonFormatter != null) 
       JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
     } 

和控制器:

[System.Web.Http.HttpPost] 
[System.Web.Http.Route("api/addjob")] 
[EnableCors(origins: "http://localhost", headers: "*", methods: "*")] 
public void AddJob([FromBody] Job job) 
{ 
    using (_tmsPortalDb) 
    { 
     _tmsPortalDb.Jobs.Add(job); 
     _tmsPortalDb.SaveChanges(); 
    } 
} 

URL都是localhost,但運行在不同的端口上,在同一個VS解決方案中都與單獨的項目一樣。我對CORs支持的理解是,這應該解決本地主機調試的問題。有什麼我錯過了嗎?

+1

只是胡亂猜測:如果你添加你的web應用主機的端口? (EnableCors(origin:「http:// localhost:SomeOthePort」,headers:「*」,methods:「*」)]' –

回答

0

如果在IIS中託管,請嘗試使用下面的代碼。

 config.EnableCors(new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true }); 

對於OWIN以下託管在我的角度應用程序的配置與的WebAPI

public class Startup { 

    public void Configuration(IAppBuilder app) { 

     AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject; 

     JwtSecurityTokenHandler.InboundClaimTypeMap.Clear(); 

     var config = new HttpConfiguration(); 
     app.UseCors(CorsOptions.AllowAll); 

     //Middleware for security. This will introspect the incoming reference token 
     IdentityServerBearerTokenAuthenticationOptions _options = new IdentityServerBearerTokenAuthenticationOptions { 
      Authority = ConfigurationManager.AppSettings["IdentityServerURI"], 
      ValidationMode = ValidationMode.ValidationEndpoint, 
      RequiredScopes = new[] { "xxxxxadmin" }, 
      ClientId = "xxxxxadmin", 
      ClientSecret = "api-secret", 
      EnableValidationResultCache = true, 
      ValidationResultCacheDuration = TimeSpan.FromMinutes(10)     
     }; 

     app.UseIdentityServerBearerTokenAuthentication(_options); 

     //Boots up the application 
     Bootstraper.BootUp(config, app); 
    } 
}