0

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.

2
  • where is the TestPayload class ? are you sure you are calling the method with correct post data ? seems like you are sending wrong data. Commented Mar 1, 2019 at 9:17
  • 1
    Based on the route attributes on the .net api controller, you are calling the wrong URL. So the not found error is accurate. You need to POST to api/test or change the route templates on the controller to match the intended URL. Commented Mar 1, 2019 at 21:47

2 Answers 2

5

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]")]
Sign up to request clarification or add additional context in comments.

Comments

0

Try to add:

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

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

More info on Microsoft-Website

1 Comment

Can you explain why CORS rules would help? Normally an OPTIONS call would fail if CORS is wrong, rather than producing a 404 (NotFound).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.