简体   繁体   English

Web API 2.0上的CORs请求

[英]CORs Request on Web API 2.0

I have enabled CORs on a Web API and on Chrome the GET and POST requests both fail but on the MS Edge browser, the GET request works with no issue but when I try a POST request, it fails with two error messages in the console: 我在Web API和Chrome上启用了COR,GET和POST请求都失败了,但在MS Edge浏览器上,GET请求没有问题,但是当我尝试POST请求时,它在控制台中失败并显示两条错误消息:

The request could not be processed by the server due to invalid syntax. 由于语法无效,服务器无法处理该请求。

XMLHttpRequest: Network Error 0x80070005, Access is denied. XMLHttpRequest:网络错误0x80070005,访问被拒绝。

The code of the post is a standard Ajax request with cross domain enabled: 帖子的代码是一个标准的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);
    }
});

And on the Web API side I have installed the CORs Nuget package and added the following to enable the code: 在Web API方面,我安装了CORs Nuget包,并添加了以下内容以启用代码:

WebApiConfig.cs 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();
        }

And the Controller: 和控制器:

[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();
    }
}

The URL's are both localhost, but running on different ports, there are both in the same VS Solution as separate projects. URL既是localhost,又是在不同的端口上运行,在同一VS解决方案中都有单独的项目。 My understanding of the CORs support is that this should solve the issue for localhost debugging. 我对CORs支持的理解是,这应解决localhost调试的问题。 Is there something I've missed? 有没有我错过的东西?

Try using the below if hosted in IIS. 如果在IIS中托管,请尝试使用以下内容。

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

For OWIN Hosted below is the config in my angular app with webapi 对于OWIN Hosted下面是我的角度应用程序中使用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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM