【问题标题】:How to handle optional query string parameters in Web API如何处理 Web API 中的可选查询字符串参数
【发布时间】:2013-04-10 11:24:07
【问题描述】:

我正在编写一个 Web API,我希望了解处理可选查询字符串参数的最佳方法是什么。

我有一个方法定义如下:

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

我可以通过在帖子正文中提供用户对象并可选地提供任何其他查询字符串值来调用它,但是当我遇到一次性随机案例时,这是解析的最佳方式吗?各种参数?
如果我有同样的场景,但有 15 个可选参数(可能是极端情况)怎么办?

【问题讨论】:

    标签: c# c#-4.0 asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    您应该使用包含所有可能参数的视图模型。然后让您的 API 方法将此视图模型作为参数。并且永远不要在您的操作中触及原始查询字符串:

    public class UserViewModel
    {
        public string CreatedBy { get; set; }
        public string AppId { get; set; }
        public int? TimeoutInMinutes { get; set; }
    
        ... other possible parameters
    }
    

    然后在您的操作中,您可以将视图模型映射到域模型:

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

    【讨论】:

    • 真的,即使是 web api?太棒了,我得试试看
    • 是的,视图模型是所有问题的答案。它们就像数字 42。
    • API 文档在这种情况下是否有用?我发现只有原始参数才能与生成的帮助文档一起使用。
    • @DarinDimitrov 需要什么样的路由才能使其正常工作?
    • @Mr.Manager 我认为您必须在 viewmodel 参数前使用 [FromUri] 。即:([FromUri] UserViewModel userModel)
    【解决方案2】:

    您将使用 ViewModel,它基本上是封装在单个对象中的客户端和服务器之间传递的所有参数的集合。 (这是MVVM中的VM)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-05
      • 2020-01-06
      • 2020-08-26
      • 2015-02-02
      • 2017-08-11
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      相关资源
      最近更新 更多