2013-04-17 34 views
3

我正在编写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); 
    } 

我能够通过在后体供给用户对象和任选提供任何额外的查询字符串值的调用此,但此解析当我有一个随机的参数分类案例时,最好的方法是什么?
如果我有这个相同的场景,但是有15个可选参数(可能是极端情况)会怎样?

回答

5

您应该使用包含所有可能参数的视图模型。然后让你的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); 
} 
+0

真的,即使是web api?酷,我必须试试 – earthling

+7

是的,查看模型是所有问题的答案。它们就像数字42. –

+0

虽然API文档在这种情况下是否有助于工作?我发现只有原始参数可以与生成的帮助文档一起工作。 – Dzejms

2

你会使用一个ViewModel,这是基本上是封装在单个对象中的客户端和服务器之间传递的所有参数的集合。 (这是MVVM中的虚拟机)

相关问题