如何处理Web API中的可选查询字符串参数
本文关键字:查询 参数 字符串 API 何处理 处理 Web | 更新日期: 2023-09-27 18:09:35
我正在编写一个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);
}
我可以通过在post主体中提供user对象并可选地提供任何额外的查询字符串值来调用它,但是当我有一个随机的参数分类的一次性情况时,这种解析是最好的方法吗?
如果我有相同的场景,但有15个可选参数(可能是极端情况),会怎么样?
您应该使用包含所有可能参数的视图模型。然后让你的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);
}
您将使用ViewModel,它基本上是封装在单个对象中的客户机和服务器之间传递的所有参数的集合。(这是MVVM中的虚拟机)