栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在ASP.NET MVC中路由,在URL中显示用户名

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在ASP.NET MVC中路由,在URL中显示用户名

就其本身而言,您的路由将不起作用,因为如果url

.../Product
意味着您想要导航至的
Index()
方法
ProductController
,则它将与您的第一个路由匹配(并假设“
Product”为
username
。您需要向您的路线添加路由约束
true
如果
username
有效,
false
则返回定义,否则无效(在这种情况下,它将尝试以下路线查找匹配项)。

假设您有

UserController
以下方法

// match http://..../Bryanpublic ActionResult Index(string username){    // displays the home page for a user}// match http://..../Bryan/Photospublic ActionResult Photos(string username){    // displays a users photos}

然后您需要定义路线

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为

.../Bryan
,则它将与
User
路由匹配,并且您将在中执行
Index()
方法
UserController
(并且的值
username
将为
"Bryan"

如果url为

.../Stephen/Photos
,则它将与
UserPhotos
路由匹配,并且您将在中执行
Photos()
方法
UserController
(并且的值
username
将为
"Stephen"

如果url为

.../Product/Details/4
,则对于前两个路由定义,路由约束将返回false,并且您将执行的
Details()
方法
ProductController

如果url为

.../Peter
or
.../Peter/Photos
且没有用户使用,
username = "Peter"
则它将返回
404Not Found

请注意,上面的示例代码对用户进行了硬编码,但实际上,您将调用返回包含有效用户名的集合的服务。为了避免打入数据库的每个请求,您应该考虑使用

MemoryCache
来缓存集合。该代码将首先检查它是否存在,如果不存在,则检查集合中是否包含
username
。如果添加了新用户,您还需要确保缓存无效。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/411944.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号