简体   繁体   中英

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

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);
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM