如何在Mvc中创建可选参数url

时间:2017-07-26 08:20:51

标签: asp.net-mvc

如果无法解决问题,请不要投票否定,因为我知道你回答的问题,这就是为什么我最后在这里。

控制器

[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

2 个答案:

答案 0 :(得分:1)

您不能,因为RouteConfig中的网址具有特定格式: {控制器} / {行动} / {ID}

要获取所需的网址,您可以创建公共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 }
        );
    }
}

答案 1 :(得分:0)

假设您使用以下方法 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”)

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

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