ASP.NET Web API CORS not working with AngularJS

I have an ASP.NET Web API running locally on some port, and I have an angularjs application running on 8080. I want to access the api from the client.

I can successfully log in and register my application because in my OAuthAuthorizationProvider it explicitly sets the response headers at the / Token endpoint.

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

It's good. However, my other API methods do not work. In my WebApiCongig.Register, I enable CORS and add the EnableCors attribute to my controllers to allow all origin, all headers and all methods. I can set a breakpoint in my get method on the controller, and it gets into the penalty box. Here's what I found while watching the Network tab in chrome.

2 requests are sent to the same api method. One type of OPTIONS method and one type of GET method. OPTIONS request header includes these two lines

Access-Control-Request-Headers: accept, authorization

Access-Control-Request Method: GET

And the answer includes these lines

Access-Control-Allow-Headers: Permission

Access-Control-Allow-Origin: *

However, requesting a GET method looks completely different. It returns to normal with a status code of 200, but it does not include or receive control headers in the request or response. And, as I said, it just hits the API. I can even do a POST and save it to the database, but the client complains about the answer !!

SO . Microsoft.AspNet.Cors 5.2.2. AngularJS 1.3.8. $resource service $http, , , .

, , .

, -API Fiddler / Postman, Bearer.

+4
3

. , . , .

.

public class CorsPolicyProvider : Attribute, ICorsPolicyProvider
{
    private CorsPolicy _policy;

    public CorsPolicyProvider()
    {
        // Create a CORS policy.
        _policy = new CorsPolicy
        {
            AllowAnyMethod = true,
            AllowAnyHeader = true,
            AllowAnyOrigin = true
        };

       // Magic line right here
        _policy.Origins.Add("*");

    }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(_policy);
    }
}

. ? , EnableCors ? . , , , . !! . , api, .

[Authorize]
[RoutePrefix("api/LicenseFiles")]
[CorsPolicyProvider]
//[EnableCors(origins: "*", headers: "*", methods: "*")] does not work!!!!!  at least I couldn't get it to work
public class MyController : ApiController
{
+1

, Options.

Web API Options, , CORS.

, , , . , :

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}

, , APIs, GET POST, . , DELETE API, . , .

Cors web.config config.EnableCors(cors);

, <system.webServer> node.

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
 </httpProtocol>

, , *. , * .

+11

, , Identity AppPool IIS ApplicationPoolIdentity NetworkService, CORS .

0

Source: https://habr.com/ru/post/1568772/


All Articles