0

Below is an Asp.net Core WebAPI which returns bad request. It works successfully when I call the web api via postman. but it doesn't work when I call with angular.

    [HttpPost]
    [Route("Login")]
    public async Task<ActionResult> Post([FromBody]LoginCommand command)
    {
        var result = await Mediator.Send(command);

        if (!result.Succeeded)
        {
            return BadRequest(result.Errors);
        }

        return Ok(result.Data);
    }

The response is being handled at the Angular side as follows:

login.services.ts

login(input: Login): Observable<any> {
let result;
this.apiService.post(this.loginPath, input).subscribe(
  data => {
    result = data;
    console.log("This should be the response???: ", data);
  },
  err => {
    console.log("err: ", err);
  });
return result;

}

api.services.ts

post(url: string, data: Object = {}): Observable<any> {

const headers = { 'Accept': '*/*', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, HEAD','Content-Type': 'application/json', 
'Access-Control-Allow-Headers': 'X-Requested-With,content-type' }

let result = this.http.post<any>(`${this.apiURL}${url}`, JSON.stringify(data), { headers });
console.log(result);
return result;

}

Console error messages:

enter image description here

Network:

enter image description here

burak ramazan
  • 146
  • 3
  • 15
  • 1
    could you please set your chrome to english and retake the screenshots? The browser console output is crucial to helping you. – kacase Mar 30 '20 at 10:32
  • 1
    It looks like a CORS issue. Is the service running in a different application than the client? – Crowcoder Mar 30 '20 at 10:36
  • Looks like your OPTIONS request is returning a 204. Are you sure about the API endpoint URL, esp the port numbers to be sure that you are running the API in the same url that your UI points to? – Saravanan Mar 30 '20 at 10:37
  • https://stackoverflow.com/a/48464030/8385590 – GoranSu Mar 30 '20 at 11:44
  • Yes, service running in a different application than the client. – burak ramazan Mar 30 '20 at 12:59

1 Answers1

1

You need to configure CORS in your asp.net core web api project startup.cs, add app.UseCors() between app.UseRouting() and app.UseEndpoints() if you are using asp.net core 3.0+:

app.UseRouting();

app.UseCors( builder => 
{ 
  builder.WithOrigins("https://localhost:5001")   
         .AllowCredentials() 
         .AllowAnyMethod() 
         .AllowAnyHeader(); 
});

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

Refer to https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware

Ryan
  • 19,118
  • 10
  • 37
  • 53