earthling
earthling

Reputation: 5264

How to handle optional query string parameters in Web API

I'm writing a Web API and I'm hoping to learn what the best way to handle optional query string parameters is.

I have a method defined below:

    [HttpPost]
    public HttpResponseMessage ResetPassword(User user)
    {
        var queryVars = Request.RequestUri.ParseQueryString();
        int createdBy = Convert.ToInt32(queryVars["createdby"]);
        var appId = Convert.ToInt32(queryVars["appid"]);
        var timeoutInMinutes = Convert.ToInt32(queryVars["timeout"]);

        _userService.ResetPassword(user, createdBy, appId, timeoutInMinutes);
        return new HttpResponseMessage(HttpStatusCode.OK);
    }

I'm able to call this by supplying the user object in the post body and optionally supplying any of the additional query string values, but is this parsing the best way to go when I have a one-off case of a random assortment of parameters?
What if I had this same scenario, but 15 optional parameters (extreme case perhaps)?

Upvotes: 4

Views: 6531

Answers (2)

paul
paul

Reputation: 22011

You would use a ViewModel, which is basically a collection of all of the parameters passed between client and server encapsulated in a single object. (This is the VM in MVVM)

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You should use a view model that will contain all the possible parameters. And then have your API method take this view model as parameter. And never touch to the raw query string in your action:

public class UserViewModel
{
    public string CreatedBy { get; set; }
    public string AppId { get; set; }
    public int? TimeoutInMinutes { get; set; }

    ... other possible parameters
}

and then in your action you could map the view model to the domain model:

[HttpPost]
public HttpResponseMessage ResetPassword(UserViewModel userModel)
{
    User user = Mapper.Map<UserViewModel, User>(userViewModel);
    _userService.ResetPassword(user, userModel.CreatedBy, userModel.AppId, userModel.TimeoutInMinutes);
    return new HttpResponseMessage(HttpStatusCode.OK);
}

Upvotes: 6

Related Questions