userone
userone

Reputation: 321

C# Controller using MediatR

I'm trying to setup a controller in C# using MediatR but my endpoint is not being hit. Here's my controller:

[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
   private readonly IMediator _mediator;

   public TestController(IMediator mediator)
   {
      _mediator = mediator;
   }

   [HttpPost]
   public async Task<IActionResult> TestReceiver([FromBody] User user)
   {
      return Accepted();
   }
}

My startup file

public class Startup : FunctionStartup //(will also be using AzureFunctions later)
{
   public override void Configure(IFunctionsHostBuilder builder)
   {
      builder.Services.AddMediatr(typeof(TestController).Assembly);
      builder.Services.AddControllers();
   }
}

When I test this in postman using the following link:(x is replaced my numbers of course)

POST: http://localhost:xxxx/api/test

It returns a 404.

What am I missing?

Upvotes: 0

Views: 1413

Answers (2)

Amir
Amir

Reputation: 1274

this error is not related to MediatR. You may have an error in postman api-call. Use postman like this:

1- url: http://localhost:xxxx/api/test

2- method: POST body:

  • raw
  • mediaType: JSON (from the combobox located at the end)
  • content: (json object of the user model like): {"Name": "test"}

Note: I assumed that your user entity has an attribute named "Name".

Upvotes: 1

Michał Jarzyna
Michał Jarzyna

Reputation: 1906

MediatR is not changing your API endpoints or routing so the issue is not here.

The most common mistake is to provide wrong body (not matching to your User model) when you are making POST requests (URL seems ok as long as you are using correct port) - web api is not able to match your request and returning 404.

If not, check if you have proper routing configuration https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1

Upvotes: 1

Related Questions