我有一个控制器,它有以下声明
[Authorize(Roles = Role.Admin)]
[ApiController]
[Route("meta/[controller]")]
public class ActionParameterController : BaseController<ActionParameterController>
在它里面有以下方法
[HttpPost("insert/{action}/{entity}")]
public IActionResult InsertActionParameter(
[FromBody] MetaActionParameter parameter,
int action,
int entity)
但是,当我尝试对这个端点执行POST请求时,我得到404。网址:
http://localhost:5000/meta/actionParameter/insert/2/2
控制台输出是:
2021-08-19 14:03:35.311 (Microsoft.AspNetCore.Hosting.Diagnostics.POST) [Information] Request starting HTTP/1.1 POST http://192.168.14.104:5000/meta/actionParameter/insert/1/2 - 0
2021-08-19 14:03:38.116 (Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware.) [Verbose] All hosts are allowed.
2021-08-19 14:03:38.117 (Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.POST) [Debug] "POST" requests are not supported
2021-08-19 14:03:38.120 (Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.POST) [Debug] "POST" requests are not supported
2021-08-19 14:03:38.125 (Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.POST) [Debug] "POST" requests are not supported
2021-08-19 14:03:38.132 (Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.) [Debug] AuthenticationScheme: "Bearer" was not authenticated.
2021-08-19 14:03:38.180 (Microsoft.AspNetCore.Routing.Matching.DfaMatcher.) [Debug] No candidates found for the request path '"/meta/actionParameter/insert/1/2"'
2021-08-19 14:03:38.182 (Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.) [Debug] Request did not match any endpoints
2021-08-19 14:03:38.185 (Microsoft.AspNetCore.Server.Kestrel.) [Debug] Connection id ""0HMB303OBKKOL"" completed keep alive response.
2021-08-19 14:03:38.191 (Microsoft.AspNetCore.Hosting.Diagnostics.POST) [Information] Request finished HTTP/1.1 POST http://192.168.14.104:5000/meta/actionParameter/insert/1/2 - 0 - 404 0 - 2880.056
我试着从IActionDescriptorCollectionProvider
获取所有的路线,路线被打印出来了。在控制器中还有其他可行的路线。
如果我将路径更改为“只插入”,则请求将通过。据我所见,两条路线之间并无冲突。
我应该采取什么进一步的步骤来诊断这个问题?
发布于 2021-08-19 11:39:13
这里有一个类似的问题:C# Web Api 2 PUT and POST requests "not supported"
基于此,看起来您不应该使用FromBody。
因此,您的方法签名应该如下所示:
[HttpPost("insert/{action}/{entity}")]
public IActionResult InsertActionParameter(int action, int entity)
为了准备请求的主体,您可以这样做:
var bodyStr = "";
var req = context.HttpContext.Request;
// Allows using several time the stream in ASP.Net Core
req.EnableRewind();
// Arguments: Stream, Encoding, detect encoding, buffer size
// AND, the most important: keep stream opened
using (StreamReader reader
= new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
{
bodyStr = reader.ReadToEnd();
}
// Rewind, so the core is not lost when it looks the body for the request
req.Body.Position = 0;
// Do whatever work with bodyStr here
https://stackoverflow.com/questions/68846708
复制相似问题