Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Web API中处理可选查询字符串参数_C#_C# 4.0_Asp.net Mvc 4_Asp.net Web Api - Fatal编程技术网

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

C# 如何在Web API中处理可选查询字符串参数,c#,c#-4.0,asp.net-mvc-4,asp.net-web-api,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["created

我正在编写一个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个可选参数(可能是极端情况)?

您应该使用包含所有可能参数的视图模型。然后让您的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);
}
[HttpPost]
公共HttpResponseMessage重置密码(UserViewModel userModel)
{
User=Mapper.Map(userViewModel);
_重置密码(user,userModel.CreatedBy,userModel.AppId,userModel.TimeoutInMinutes);
返回新的HttpResponseMessage(HttpStatusCode.OK);
}

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

真的,即使是web api?酷,我得试一下,视图模型是所有问题的答案。它们就像数字42。API文档在这种情况下有帮助吗?我发现只有原语参数才能与生成的帮助文档一起工作。@DarinDimitrov要使其工作,路由需要是什么样子?@Mr.Manager我想您必须在viewmodel参数前面使用[FromUri]。Ie:([FromUri]用户视图模型用户模型)