Return an error when invalid parameters are specified in ASP Web API

前端 未结 3 1210
长情又很酷
长情又很酷 2021-01-26 15:03

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.

For example:

/api/Eve         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-26 15:45

    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.

    You may use it like this:

    [InvalidQueryStringRejector]
    public IHttpActionResult Get(string value)
    {
        return Ok(value);
    }
    

    Or apply to any action by registering it inside your HttpConfiguration object:

    config.Filters.Add(new InvalidQueryStringRejectorAttribute());
    

提交回复
热议问题