4

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

2 Answers 2

6

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

8 Comments

really, even for web api? Cool, I'll have to give that a try
Yes, view models are the answer to all problems. They are like the number 42.
Does the API documentation help stuff work in this case though? I've found that only primitive params work with the generated help docs.
@DarinDimitrov what is the routing going to need to look like for this to work?
@Mr.Manager I think you have to use [FromUri] in front of your viewmodel parameter. Ie: ([FromUri] UserViewModel userModel)
|
2

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)

Comments

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.