简体   繁体   中英

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:

The request could not be processed by the server due to invalid syntax.

XMLHttpRequest: Network Error 0x80070005, Access is denied.

The code of the post is a standard Ajax request with cross domain enabled:

$.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:

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. My understanding of the CORs support is that this should solve the issue for localhost debugging. Is there something I've missed?

Try using the below if hosted in IIS.

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

For OWIN Hosted below is the config in my angular app with 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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