如何处理在网页API可选的查询字符串参数 [英] How to handle optional query string parameters in Web API

查看:104
本文介绍了如何处理在网页API可选的查询字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个Web API,我希望能学到什么是最好的方式来处理可选的查询字符串参数。

I'm writing a Web API and I'm hoping to learn what the best way to handle optional query string parameters is.

我有以下定义的方法:

    [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可选参数(极端情况下可能)?

I'm able to call this by supplying the user object in the post body and optionally supplying any of the additional query string values, but is this parsing the best way to go when I have a one-off case of a random assortment of parameters?
What if I had this same scenario, but 15 optional parameters (extreme case perhaps)?

推荐答案

您应该使用将包含所有可能的参​​数视图模型。再有你的API方法采取这种观点模型参数。而从来没有接触到原始查询字符串在动作:

You should use a view model that will contain all the possible parameters. And then have your API method take this view model as parameter. And never touch to the raw query string in your action:

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

    ... other possible parameters
}

,然后在你的行动,你可以映射视图模型域模型:

and then in your action you could map the view model to the domain model:

[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);
}

这篇关于如何处理在网页API可选的查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆