问题描述
我正在使用 C# 和 ASP.NET Web API 创建 API,我希望它在使用无法识别的参数时返回错误.
I'm creating an API using C# and ASP.NET Web API and I want it to return an error when a parameter is used that isn't recognised.
例如:
/api/Events
应该是事件列表
/api/Events?startTime={{startTime}}
应该返回在特定时间开始的事件列表
should return a list of events that started at a particular time
/api/Events?someRandomInvalidParameter={{something}}
应该返回一个错误
有没有好的配置方式来做到这一点?如果没有,我怎样才能得到一个参数列表来检查自己.
Is there a nice config way to do this? If not, how can I get a list of parameters to check myself.
推荐答案
您可以创建一个 ActionFilter
来自动执行此操作:
You could create an ActionFilter
to automate this:
public class InvalidQueryStringRejectorAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var arguments = actionContext.ActionArguments.Keys;
var queryString = actionContext.Request.GetQueryNameValuePairs()
.Select(q => q.Key);
var invalidParams = queryString.Where(k => !arguments.Contains(k));
if (invalidParams.Any())
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, new
{
message = "Invalid query string parameters",
parameters = invalidParams
});
}
}
}
该过滤器将拒绝任何查询字符串参数与方法签名不匹配的请求.
That filter will reject any request with query string parameters that do not match the method signature.
你可以这样使用它:
[InvalidQueryStringRejector]
public IHttpActionResult Get(string value)
{
return Ok(value);
}
或者通过将其注册到您的 HttpConfiguration
对象中来应用于任何操作:
Or apply to any action by registering it inside your HttpConfiguration
object:
config.Filters.Add(new InvalidQueryStringRejectorAttribute());
这篇关于在 ASP Web API 中指定无效参数时返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!