0

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.

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

Comments

1

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'.

4 Comments

Thanks, Anton. Should this work even in the case where one parameter is valid and one is not? e.g. /api/alive?id=1&blablabla=1 From my limited testing, if I have at least one valid parameter it will still bind to one of my Get methods - could it be because I am using some optional parameters? string startTime = ""
Yes it will work because Action will try to find id parameter and will ignore all others. Even localhost:1578/api/alive?qwe=2&id=1 will work.
How can I make it not work? I want the user to be notified if they add qwe=2 and it doesn't do anything.
Wait a bit i will investigate this, in my opinion we should change routes
0

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

2 Comments

Hi Phong, I want to use parameters because I don't want to explicitly set the URL like that. What if I want to have more than one optional parameter? What about ordering? Also I don't know in advance what invalid parameters people might use.
This parameter is match with position of value that user input in URL.localhost:8080/app/Events/19901101 localhost:8080/app/Events/19901101/something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.