Return an error when invalid parameters are specified in ASP Web 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.

For example:

/api/Events

should a list of events

/api/Events?startTime={{startTime}}

should return a list of events that started at a particular time

/api/Events?someRandomInvalidParameter={{something}}

should return an error

Is there a nice config way to do this? If not, how can I get a list of parameters to check myself.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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());

Method 2

try strongly typed actions like this

  public string Get()
        {
            return "I'm alive empty";
        }

  public string Get([FromUri] int id)
        {
            return "I'm alive";
        }

So normal call will return I’m alive or I’m alive empty

  http://localhost:1578/api/alive?id=1 //OR
  http://localhost:1578/api/alive

But if you try to call it like this

http://localhost:1578/api/alive?blablabla=1

You will occure this error

The requested resource does not support http method ‘GET’.

Method 3

I think you should be override methods
Example:

[Route("/app/Events/{startTime})"]
public ApiResponse Get(string startTime)
{
}
[Route("/app/Events/{startTime}/{someRandomeInvalid}")]
public ApiResponse Get(string startTime, string someRandomeInvalid)
{
}

Don’t set explicit parameters name. You should be manage/check by order of parameter


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x