简体   繁体   中英

404 error when making a POST call from Angular HttpClient to ASP.NET Core 2.2 Web API (with CORS enabled)

I've written a simple ASP.NET Core 2.2 Web API . The POST method always returns a 404 , but GET requests succeed.

public class TestPayload
{
    public string test1 { get; set; }
    public string test2 { get; set; }
}

[Route("api/[controller]")]
[ApiController]
public class TestController: ControllerBase
{        
    // POST api/create
    [HttpPost]
    public async Task<ActionResult<string>> Create([FromBody] TestPayload value)
    {
        return Ok("");
    }
}

I get back a 404 error in my Angular HttpClient front-end.

let headers = new HttpHeaders().set('Content-Type', 'application/json');

return this.http.post<any>(`${config.apiUrl}/test/create`, { test1, test2}, { headers }).pipe(map(x => {
                        ...               
                        return x;
                       }));

I get the same error in Postman.

POST /api/Test/Create HTTP/1.1
Host: localhost:5001
Content-Type: application/json
cache-control: no-cache
Postman-Token: 4d304e86-013c-4be8-af07-f2262079000d
{ test1: "val1", test2: "val2" }------WebKitFormBoundary7MA4YWxkTrZu0gW--

I have enabled the most permissive CORS policies (to test with) in my Startup.cs file, but it doesn't fix the issue.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder =>
            {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            });
    });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);       
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }
    app.UseCors("AllowAll");
    app.UseHttpsRedirection();
    app.UseMvc();
}

I see the following message in the Output window in Visual Studio, which leads me to believe it is a CORS error, but I don't know what I have done wrong. My breakpoints inside the method never get hit, even though symbols are loaded and they are hit in the GET methods.

Microsoft.AspNetCore.Server.Kestrel:Information: Connection id "0HLKU1LFDTCPA", Request id "0HLKU1LFDTCPA:00000002": the application completed without reading the entire request body.

This is running all on localhost. I have installed Microsoft.AspNetCore.Cors (2.2.0) NuGet package in my project.

You have not specified a route to the action. You can either change your post to go to /api/Test or set the attributes on the action as follows:

[HttpPost("Create")]
public async Task<ActionResult<string>> Create([FromBody] TestPayload value)
{
    return Ok("");
}

or

[HttpPost]
[Route("Create")]
public async Task<ActionResult<string>> Create([FromBody] TestPayload value)
{
    return Ok("");
}

or update the controller route to include the action

[Route("api/[controller]/[action]")]

Try to add:

[EnableCors(origins: " * ", headers: " * ", methods: " * ")]

to your Controller class. ( remove with spaces in the quotes )

More info on Microsoft-Website

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