在ASP Web API中指定无效参数时返回错误 [英] Return an error when invalid parameters are specified in ASP Web API

查看:125
本文介绍了在ASP Web API中指定无效参数时返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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中指定无效参数时返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆