【问题标题】:Getting "405 Method Not Allowed" from post request to .Net Core 3.1 API从发布请求到.Net Core 3.1 API 获取“405 Method Not Allowed”
【发布时间】:2021-10-11 11:35:24
【问题描述】:

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

我有一个 post 端点,它应该从请求的正文中获取一个 json 对象并用它做一些事情,但我从来没有到达我的端点,当我在 postman 中测试它时只得到响应“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; }
    }

Startup.cs:

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

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

【问题讨论】:

    标签: c# json .net-core asp.net-core-webapi asp.net-core-3.1


    【解决方案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

    【讨论】:

    • 谢谢。我知道这将是一件非常简单的事情。我在 .Net Framework 中的路由完全没有问题,但由于某种原因,自从切换到 Core 后,我似乎无法正确处理。
    • 现在接受。你回答得这么快,我一开始不被允许!
    猜你喜欢
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2014-09-03
    • 2020-01-08
    • 2012-06-22
    • 2014-11-26
    • 2015-07-29
    • 2011-11-17
    相关资源
    最近更新 更多