2017-06-22 134 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); 
    } 
}