微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何在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);
    }

我可以通过在post主体中提供用户对象并可选地提供任何其他查询字符串值来调用它,但是当我有一个随机分类参数的一次性情况时,这是解析的最佳方式?
如果我有相同的情况,但有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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐