繁体   English   中英

Web API 2.0上的CORs请求

[英]CORs Request on Web API 2.0

我在Web API和Chrome上启用了COR,GET和POST请求都失败了,但在MS Edge浏览器上,GET请求没有问题,但是当我尝试POST请求时,它在控制台中失败并显示两条错误消息:

由于语法无效,服务器无法处理该请求。

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支持的理解是,这应解决localhost调试的问题。 有没有我错过的东西?

如果在IIS中托管,请尝试使用以下内容。

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

对于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