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

ear*_*ing 3 c# c#-4.0 asp.net-mvc-4 asp.net-web-api

我正在编写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);
    }
Run Code Online (Sandbox Code Playgroud)

我可以通过在post主体中提供用户对象并可选地提供任何其他查询字符串值来调用它,但是当我有一个随机分类参数的一次性情况时,这是解析的最佳方式?
如果我有相同的情况,但有15个可选参数(可能是极端情况)怎么办?

Dar*_*rov 5

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

public class UserViewModel
{
    public string CreatedBy { get; set; }
    public string AppId { get; set; }
    public int? TimeoutInMinutes { get; set; }

    ... other possible parameters
}
Run Code Online (Sandbox Code Playgroud)

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

[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);
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,查看模型是解决所有问题的答案.他们就像42号. (7认同)
  • @ Mr.Manager我想你必须在viewmodel参数前面使用[FromUri].即:([FromUri] UserViewModel userModel) (2认同)