Reputation: 141
I'm developing a new web api in .Net Core, having previously worked with .Net Framework.
I have a post endpoint that should take a json object from the body of the request and does some stuff with it, but I never reach my endpoint and only get the response "405 Method Not Allowed" when I test it in postman.
Controller:
[Route("api/[controller]")]
[ApiController]
public class PageHitController : ControllerBase
{
private IMongoCollection<PageHit> pageHitsCollection;
public PageHitController(IMongoClient _client)
{
var mongoDB = _client.GetDatabase("POC_MongoDB");
pageHitsCollection = mongoDB.GetCollection<PageHit>("PageHits");
}
[HttpPost]
[Route("api/pagehit")]
public async Task<ActionResult> AddPageHit([FromBody] PageHit pageHit)
{
// Do Stuff
return Ok();
}
}
Expected object:
[BsonIgnoreExtraElements]
public class PageHit
{
[BsonId]
public Guid ID { get; set; }
[BsonElement("clientid")]
public Guid ClientID { get; set; }
[BsonElement("domain")]
public string Domain { get; set; }
[BsonElement("sessionid")]
public string SessionID { get; set; }
[BsonElement("url")]
public string Url { get; set; }
[BsonElement("pagesize")]
public int PageSize { get; set; }
}
Startup.cs:
services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
builder
.WithMethods("GET", "POST")
.AllowAnyHeader()
.AllowAnyOrigin();
}));
Please can you help me. All my GET endpoints are working fine, but this POST is not.
Upvotes: 1
Views: 1267
Reputation: 43959
you have to fix the action route attribute. You can remove [Route("api/pagehit")] attribute, make it default action
[HttpPost]
public async Task<ActionResult> AddPageHit([FromBody] PageHit pageHit)
or fix the route attribute
[HttpPost]
[Route("~/api/addpagehit")]
public async Task<ActionResult> AddPageHit([FromBody] PageHit pageHit)
in this case you will have to change pagehit to addpagehit in postman too
Upvotes: 3