簡體   English   中英

如何在Web API中處理可選的查詢字符串參數

[英]How to handle optional query string parameters in 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);
}

您將使用ViewModel,它基本上是封裝在單個對象中的客戶端和服務器之間傳遞的所有參數的集合。 (這是MVVM中的VM)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM