Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 781
earthling Avatar asked Oct 27 '25 04:10

earthling


2 Answers

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);
}
like image 87
Darin Dimitrov Avatar answered Oct 29 '25 18:10

Darin Dimitrov


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)

like image 28
paul Avatar answered Oct 29 '25 18:10

paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!