c# - 从发布请求到.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 不是。
解决方案
您必须修复 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
推荐阅读
- javascript - 谷歌分析页面数据和 api 响应之间是不同的
- windows - 在 Windows 7 中从命令行控制鼠标设置
- python - 查找特定 k-means 集群的大小
- python - Python 输入,命名元组在调用 _asdict() 时缺少默认值
- highcharts - 带类别的Highchart折线图不占全宽
- java - 如何扫描用户输入以确认执行 DELETE 操作
- mongodb - 如何简单地将两个集合合二为一并删除mongoDB中的重复
- windows - Windows 网络列表管理器 API 返回不正确的连接信息
- sql - DolphinDB 远程访问异常,找不到名为 loadTable('dfs://zctestDB','trainInfoTable') 的对象
- restsharp - 当请求可能返回不同对象时响应的反序列化