angularcorshttp-posthttpclientwebapi

“Http failure response for (unknown url): 0 Unknown Error” instead of actual error message in Angular


I'm totally new to Angular 6 & .NET web api. I'm trying to call post api from my angular app using HttpClient. but I'm getting CORS error:

OPTIONS http://localhost:64458/api/employee/insert 404 (Not Found)

Access to XMLHttpRequest at 'http://localhost:64458/api/employee/insert' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

core.js:15724 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:64458/api/employee/insert", ok: false, …}

Here is my angular service.ts code:

url = 'http://localhost:64458/api/employee';
constructor(private http:HttpClient) {}
httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'}) };  

insert(obj: any): Observable<any>{
    return this.http.post<any>(this.url + '/insert', obj,this.httpOptions).pipe(map(res => res));
}

Here is my web api code:

[RoutePrefix("api/employee")]
public class HomeController : ApiController
{
    [HttpPost]
    [Route("insert")]
    public IHttpActionResult PostEmployee(dynamic data)
    {
        try
        {
            return Ok();
        }
        catch (Exception)
        {
            throw;
        }
    }
}

What can be the issue?


Solution

  • First in the Package Manager Console window, type the following command

    Install-Package Microsoft.AspNet.WebApi.Cors
    

    Then you could enable it globally like bellow

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute("*", "*", "*");
            // or new EnableCorsAttribute("www.example.com", "*", "*");
            config.EnableCors(cors);
            // ...
        }
    }
    

    More details could be found in their DOC