【问题标题】:ASP.NET MVC Routing: Multiple parameter in URL [duplicate]ASP.NET MVC 路由:URL 中的多个参数 [重复]
【发布时间】:2016-05-27 21:24:48
【问题描述】:

我正在尝试将 Web 服务从 PHP 移植到 ASP.NET MVC。当然,这意味着我必须复制现有的 API。

目前,规范形式的调用如下:

http://example.com/book/search?title=hamlet&author=shakes

不过,它也接受另一种形式:

http://example.com/book/search/title/hamlet/author/shakes

大约有五种不同的搜索条件,都是可选的,并且可以按任意顺序给出。

如何在 ASP.NET MVC 路由中做到这一点?

【问题讨论】:

  • 很抱歉重复发布。我在“路由”下搜索并忘记检查“路由”

标签: asp.net asp.net-mvc asp.net-mvc-routing


【解决方案1】:

你可以试试这样的。

[Route("Book/search/{*criteria}")]
public ActionResult Search(string criteria)
{
    var knownCriterias = new Dictionary<string, string>()
    {
        {"author", ""},
        {"title",""},
        {"type",""}
    };
    if (!String.IsNullOrEmpty(criteria))
    {

        var criteriaArr = criteria.Split('/');
        for (var index = 0; index < criteriaArr.Length; index++)
        {

            var criteriaItem = criteriaArr[index];
            if (knownCriterias.ContainsKey(criteriaItem))
            {
                if (criteriaArr.Length > (index + 1))
                    knownCriterias[criteriaItem] = criteriaArr[index + 1];
            }
        }
    }
    // Use knownCriterias dictionary now.
    return Content("Should return the search result here :)");
}

以* 为前缀的最后一个参数就像一个catch-all 参数,它将在Book/search 之后将任何内容存储在url 中。

因此,当您请求 yoursite.com/book/search/title/nice/author/jim 时,默认模型绑定器会将值“title/nice/author/jim”映射到条件参数。您可以在该字符串上调用 Split 方法来获取 url 段数组。然后将值转换为字典并将其用于您的搜索代码。

基本上,上面的代码将从溢出的数组中读取,并根据您在 url 中传递的内容设置 knownCriteria 字典项的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多