首页 > 解决方案 > 从发布请求到.Net Core 3.1 API 获取“405 Method Not Allowed”

问题描述

我正在.Net Core 中开发一个新的 web api,之前使用过 .Net Framework。

我有一个 post 端点,它应该从请求的正文中获取一个 json 对象并用它做一些事情,但是我从来没有到达我的端点,并且当我在邮递员中测试它时只得到响应“405 Method Not Allowed”。

控制器:

    [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();
        }
    }

预期对象:

    [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; }
    }

启动.cs:

services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
    builder
    .WithMethods("GET", "POST")
    .AllowAnyHeader()
    .AllowAnyOrigin();
}));

邮递员回应

请你帮帮我。我所有的 GET 端点都工作正常,但这个 POST 不是。

标签: c#json.net-coreasp.net-core-webapiasp.net-core-3.1

解决方案


您必须修复 action route 属性。您可以删除 [Route("api/pagehit")] 属性,使其成为默认操作

 [HttpPost]
 public async Task<ActionResult> AddPageHit([FromBody] PageHit pageHit)

或者修复路由属性

 [HttpPost]
 [Route("~/api/addpagehit")]
  public async Task<ActionResult> AddPageHit([FromBody] PageHit pageHit)

在这种情况下,您也必须在邮递员中将 pagehit 更改为 addpagehit


推荐阅读