MVC路由问题 [英] MVC routing question

查看:87
本文介绍了MVC路由问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置路由如下:

/资料/编辑 - >路线编辑行动

/Profile/Edit -> routes to Edit action

/资料/添加 - >路线添加动作

/Profile/Add -> routes to Add action

/资料/用户名 - >路线与参数名索引操作,因为操作的用户名不存在

/Profile/username -> routes to Index action with parameter username, because action username doesn't exist.

所以我想第二个参数解析为控制器动作,与该名称的控制器中是否存在除;那么它应该为默认的索引页面的路线和使用url一部分ID。

So I want the second parameter to be parsed as the controller action, except when no controller with that name exists; then it should route to the default index page and use the url part as id.

可能?

推荐答案

马特的解决方案,让你90%的方式。然而,而是采用了路由约束排除操作名称,使用路由限制为只包括有效用户名,例如:

Matt's solution gets you 90% of the way. However, instead of using a route constraint to exclude action names, use a route constraint to include only valid usernames, like so:

public class MustMatchUserName : IRouteConstraint 
{ 

    private Users _db = new UserEntities(); 

    public MustMatchUserName() 
    { } 

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
        return _db.Users.FirstOrDefault(x => x.UserName.ToLower() == values[parameterName].ToString().ToLower()) != null; 
    } 
} 

然后,马特指出,在用户创建过程中,你必须强制执行的规则,你ActionNames无效用户名。

Then, as Matt points out, in the user creation process, you must enforce a rule that your ActionNames are not valid for user names.

counsellorben

counsellorben

这篇关于MVC路由问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆