在第一次正斜杠后捕获项目的路线

时间:2013-12-11 21:13:37

标签: c# asp.net-mvc-4 routing asp.net-mvc-routing

我正在艰难地尝试创建一条工作路线,让我在正斜杠之后捕捉第一个项目(之后最好没有任何东西)。

例如,www.mywebsite.com/item1,www.mywebsite.com/item2,www.mywebsite.com/item2

该项目将只是字母或数字,没有空格或其他字符。

有什么想法吗?

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute("UsernameRoute", "{Username}", new { controller = "Home", action = "GetUsername" }, new { Username = new UsernameConstraint() });

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );            
    }

并在家庭控制器中:

    public ActionResult GetUsername(string username)
    {
        ViewBag.Message = username;

        return View("Username");
    }

和路线约束文件:

public class UsernameConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return true; //set to true for now to test but will lookup username in database here
    }
}

0 个答案:

没有答案