我正在尝试创建一个带有用户名的路线...
所以URL将是mydomain.com/abrudtkhul(abrudtkhul是用户名)
我的应用程序将具有基于用户名的公共配置文件(例如:http://delicious.com/abrudtkuhl).我想复制这个URL方案.
我怎样才能在ASP.Net MVC中构建它?我也在使用会员/角色提供商.
小智 26
这是你想要做的,首先定义你的路线图:
routes.MapRoute(
"Users",
"{username}",
new { controller = "User", action="index", username=""});
Run Code Online (Sandbox Code Playgroud)
这允许您做的是设置以下约定:
因此,当您请求URL http://mydomain.com/javier时,这将转换为UserController.Index(字符串用户名)的调用,其中username设置为javier的值.
既然你计划使用MembershipProvider类,你想要更像这样的东西:
public ActionResult Index(MembershipUser usr)
{
ViewData["Welcome"] = "Viewing " + usr.UserName;
return View();
}
Run Code Online (Sandbox Code Playgroud)
为此,您需要使用ModelBinder来完成从用户名到MembershipUser类型的绑定工作.为此,您需要创建自己的ModelBinder类型并将其应用于Index方法的user参数.你的课可以看起来像这样:
public class UserBinder : IModelBinder
{
public ModelBinderResult BindModel(ModelBindingContext bindingContext)
{
var request = bindingContext.HttpContext.Request;
var username = request["username"];
MembershipUser user = Membership.GetUser(username);
return new ModelBinderResult(user);
}
}
Run Code Online (Sandbox Code Playgroud)
这允许您将Index方法的声明更改为:
public ActionResult Index([ModelBinder(typeof(UserBinder))]
MembershipUser usr)
{
ViewData["Welcome"] = "Viewing " + usr.Username;
return View();
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我们已将[ModelBinder(typeof(UserBinder))]属性应用于方法的参数.这意味着在调用方法之前,将调用UserBinder类型的逻辑,因此在调用方法时,您将拥有MembershipUser类型的有效实例.
Ste*_*nby 17
如果您想要一些其他功能控制器,如帐户,管理员,个人资料,设置等,您可能需要考虑不允许某些类型的用户名.此外,您可能希望静态内容不会触发"用户名"路由.为了实现这种功能(类似于处理twitter URL的方式),您可以使用以下路由:
// do not route the following
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("content/{*pathInfo}");
routes.IgnoreRoute("images/{*pathInfo}");
// route the following based on the controller constraints
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
, new { controller = @"(admin|help|profile|settings)" } // Constraints
);
// this will catch the remaining allowed usernames
routes.MapRoute(
"Users",
"{username}",
new { controller = "Users", action = "View", username = "" }
);
Run Code Online (Sandbox Code Playgroud)
然后,您需要为约束字符串中的每个标记(例如,管理员,帮助,配置文件,设置)以及名为Users的控制器提供控制器,当然还有本示例中Home的默认控制器.
如果您有许多您不想允许的用户名,那么您可以通过创建自定义路由处理程序来考虑更动态的方法.