简体   繁体   English

如何在Web API中处理可选的查询字符串参数

[英]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. 我正在编写Web API,我希望了解处理可选查询字符串参数的最佳方法是什么。

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? 我可以通过在post主体中提供用户对象并可选地提供任何其他查询字符串值来调用它,但是当我有一个随机分类参数的一次性情况时,这是解析的最佳方式?
What if I had this same scenario, but 15 optional parameters (extreme case perhaps)? 如果我有相同的情况,但有15个可选参数(可能是极端情况)怎么办?

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. 然后让您的API方法将此视图模型作为参数。 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. 您将使用ViewModel,它基本上是封装在单个对象中的客户端和服务器之间传递的所有参数的集合。 (This is the VM in MVVM) (这是MVVM中的VM)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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