【问题标题】:How to make optional parameter url in Mvc如何在 Mvc 中制作可选参数 url
【发布时间】:2017-08-05 15:11:35
【问题描述】:

如果不能解决问题,不要投反对票,因为我知道你的答案是什么,这就是为什么我最后在这里。

控制器

[Route("{Name}")]
    public ActionResult Details(int? id, string Name)
    {          

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Menu menu = db.Menus.Find(id);
        if (menu == null)
        {
            return HttpNotFound();
        }
        return View(menu);
    }

观看次数

@Html.ActionLink("Details", "Details", new { id = item.Id, Name = item.MenuName })

Route.config.cs

route.MapMvcAttributeRoutes();

输出:

如何获得这样的输出

localhost:2345/Blog 而不是 localhost:2345/Details/id=1?Name=Blog

【问题讨论】:

  • 您不能只得到../Blog(假设您使用默认路由,该网址将调用BlogControllerIndex() 方法)。路线需要是可区分的。无论如何,您似乎还想为id 传递一个值
  • 是的,我使用的是默认路由。我怎样才能实现它我想创建一个动态页面。所以告诉我我将如何得到这个。甚至更改 route.config.cs 或其他任何内容。
  • 你没有阅读我的评论吗?你不能。而且您的代码毫无意义。为什么在你从未使用过Name 时传递它的值。而且因为id 的值将始终为null(因为它不包含在url 中),所以您的代码将始终返回BadRequest,这有点毫无意义。
  • 我最好的猜测是你真的想要一个 slug 路线(例如按照 SO 路线),这样你就可以得到 .../Details/1/Blog` 在这种情况下参考this answer跨度>
  • 您有任何示例如何从数据库中获取动态页面。使用 localhost:2345/page 之类的 url

标签: asp.net-mvc


【解决方案1】:

您不能,因为 RouteConfig 中的 url 具有特定格式: {controller}/{action}/{id}

要获取你想要的 url,你可以创建 public ActionResult Blog()

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "NoScript",
            url : "noscript",
            defaults : new { controller = "Home", action = "EnableJavaScript"}
            );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",//the specific format
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

【讨论】:

  • 我正在创建动态页面,但不是特定的博客,我正在使用 scalffoding 获取表,并在视图部分中,例如 localhost:2345/我想要的名称
  • 你不明白我的问题,我是说假设我有 Home 控制器并且我在 Index 中有数据库列表,我想在点击详细信息或任何视图上显示该类别或列表以通过 localhost :2345/listName
【解决方案2】:

假设您有一个 UserController 具有以下方法

// match http://..../arrivaler
    public ActionResult Index(string username)
    {
        // displays the home page for a user
    }

    // match http://..../arrivaler/Photos
    public ActionResult Photos(string username)
    {
        // displays a users photos
    }

Route.config.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "User",
            url: "{username}",
            defaults: new { controller = "User", action = "Index" },
            constraints: new { username = new UserNameConstraint() }
        );
        routes.MapRoute(
            name: "UserPhotos",
            url: "{username}/Photos",
            defaults: new { controller = "User", action = "Photos" },
            constraints: new { username = new UserNameConstraint() }
        );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Test", action = "Index", id = UrlParameter.Optional }
        );
    }

    public class UserNameConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            List<string> users = new List<string>() { "Bryan", "Stephen" };
            // Get the username from the url
            var username = values["username"].ToString().ToLower();
            // Check for a match (assumes case insensitive)
            return users.Any(x => x.ToLower() == username);
        }
    }
}

如果 url 是 .../Arrivaler,它将匹配 User 路由,您将在 UserController 中执行 Index() 方法(并且用户名的值将是“Arrivaler”)

如果 url 是 .../Arrivaler/Photos,它将匹配 UserPhotos 路由,您将在 UserController 中执行 Photos() 方法(并且用户名的值将是“Arrivaler”)

注意上面的示例代码对用户进行了硬编码,但实际上您将调用一个服务,该服务返回一个包含有效用户名的集合。为了避免每次请求都访问数据库,您应该考虑使用 MemoryCache 来缓存集合。代码将首先检查它是否存在,如果不填充它,则检查集合是否包含 用户名。如果添加了新用户,您还需要确保缓存失效。

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 2013-11-14
    • 2020-10-10
    • 2013-09-29
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多