[英]How do I block invalid json request parameters in asp net core 5 controller (for POST method)
I'm creating an api in asp net core 5 and cannot figure this one out.我在 asp net core 5 中创建了一个 api 并且无法弄清楚这一点。
When sending this (via a POST call) to the Api it works as expected (200 is returned):当将此(通过 POST 调用)发送到 Api 时,它按预期工作(返回 200):
{
"existingParameterName1": "value1",
"existingParameterName2": "value2"
}
When sending this I want to block it and return 400 - Bad request发送时我想阻止它并返回 400 - 错误请求
{
"existingParameterName1": "value1",
"existingParameterName2": "value2",
"nonExistingParameterName": "value3"
}
The post handler method in the controller looks like this: controller 中的后处理程序方法如下所示:
public class MyRequestType
{
public string ExistingParameterName1 { get; set; }
public string ExistingParameterName2 { get; set; }
}
[HttpPost]
public async Task<MyResponseType> Post([FromBody] MyRequestType request)
{
// when getting here the request has been converted to MyRequestType with
// only existingParameterName1 and existingParameterName2 (no nonExistingParameterName)
// How do I detect if there is any non valid parameters in the request?
// the handling code here...
}
I have tried to do an actionfilter for this and also tried to change MyRequestType to object.我试图为此做一个动作过滤器,并尝试将 MyRequestType 更改为 object。 Both ways could work but feels wrong.
两种方法都可以,但感觉不对。 Gut feeling says there is a better way to do this.
直觉告诉我们有更好的方法来做到这一点。 What is the proper way to do this?
这样做的正确方法是什么?
Normally, API should ignore the extra input parameters and process with the passed and required one.通常,API 应该忽略额外的输入参数,并使用传递和需要的参数进行处理。
but as you are looking something to implement and want to return the "Bad Request" in case of extra passed parameters.但是当您正在寻找要实现的东西并希望在传递额外参数的情况下返回“错误请求”。
Not sure about the Asp.Net Core, but works with Asp.Net WebApi you can do this in ModelBinder, just impelement IModelBinder
and add your logic there.不确定 Asp.Net Core,但可以与 Asp.Net WebApi 一起使用,您可以在 ModelBinder 中执行此操作,只需 impelement
IModelBinder
并在那里添加您的逻辑。
IModelBinder is responsible to transform and pass your input json to Action method parameters. IModelBinder 负责将您的输入 json 转换并传递给 Action 方法参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.