I am trouble with CORS in Angular POST request


#1

Hi there,

I have problem with Angular’s POST method. I created a form and tried send data to server with Angular HTTP POST method. But in server (.NET WEB API) I see request’s header is null.

Here is the Angular side codes;


  login(username, password):Observable<Object>{

    let url : string = this.apiUrl+"/login";
    let headers = new HttpHeaders();

    headers.append('Authorization', btoa(username+":"+password).toString());

    return this.http.post(url,JSON.stringify({username,password}), {headers: headers});
  }

Here is the .NET side codes for controller;

[EnableCors(origins: "http://localhost:8100", headers: "*", methods: "*")]
public Response Post()
{
    return _mobileUserService.Login();
}

Here is the part of .NET side codes for catch request;

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                var token = request.Headers.GetValues("Authorization").FirstOrDefault();
            }

            catch (Exception ex)
            {

            }

            return base.SendAsync(request, cancellationToken);
        }

When request catched by .NET (in running), I see these values for “request” variable;

request = {Method: POST, RequestUri: 'http://localhost:41582/api/login', Version: 1.1, Content: System.Web.Http.WebHost.HttpControllerHandler+LazyStreamContent, Headers:
{
  Connection: keep-alive
  Accept: application/json
  Accept: text/plain
  Accept: */*
  ...