Home > Net >  C# .NET API Validate Query Parameters Are on Model
C# .NET API Validate Query Parameters Are on Model

Time:06-28

I have a C# .NET API that I am working on and I am hoping to validate that query parameters used in the URL are valid properties on the model I have.

I have a model that I use to define valid query parameters and take them in as below:

[HttpGet]
[Produces("application/json")]
[Route("/[controller]/getData")]
public IActionResult GetData([FromQuery] ParameterModel params)
{
    // Do Stuff
}

Say I have a property named Param1 on that model. If somebody passes that in from the URL string it works correctly and maps the data to the property. However if there is a typo like Parm1 that value is simply ignored.

I would like to return a bad request when a misnamed parameter is passed in like that so it is clear it is a bad parameter instead of simply ignoring it.

Is there a built in validation with .NET that can do this? If not I plan to write some code to handle it but would prefer to do it with out of the box options from .NET if possible.

CodePudding user response:

I think i understand your question, you want to know if your Model is valid. The correct way to do that is using:

ModelState.IsValid

My own implementation of your request would be the following:

[HttpGet]
[Produces("application/json")]
[Route("/[controller]/getData")]
public IActionResult GetData([FromQuery] ParameterModel params)
{
    //Check if current modelstate is valid, else return bad request
    if(!ModelState.IsValid)
       return BadRequest(ModelState);
    // Do Stuff
}

CodePudding user response:

Since I wasn't able to find anything built in with C#/.NET to do this, I ended up writing a method to check the parameters from the request against a model and use that for the validation:

public bool AreQueryParametersValid(ParameterModel parameters, HttpRequest request)
{
    var paramProperties = parameters.GetType().GetProperties();
    var validParams = new List<string>();

    foreach (var parameter in paramProperties)
    {
        validParams.Add(parameter.Name.ToLower());
    }

    foreach (var queryParam in request.Query.Keys)
    {
        if (!validParams.Contains(queryParam.ToLower()))
        {
            return false;
        }
    }

    return true;
}
  • Related