重定向到 MVC 中的自定义路由
Redirecting to a custom route in MVC
我在我的 MVC 站点中设置了自定义路由。不过,我无法弄清楚如何重定向到它。这是我的自定义路线代码:
public class MemberUrlConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
if (values[parameterName] != null)
{
var permalink = values[parameterName].ToString();
return string.Equals(permalink, Member.GetAuthenticatedMembersUrl(),
StringComparison.OrdinalIgnoreCase);
}
return false;
}
}
这是我的 RouteConfig.cs
文件:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "MembersRoute",
url: "{*permalink}",
defaults: new { controller = "Dashboard", action = "Index" },
constraints: new { permalink = new MemberUrlConstraint() });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
这工作正常。如果我在浏览器 URL 中输入类似 http://www.example.com/Joes-Page
的内容,它会正常工作。
我的问题是,如何以编程方式重定向到此页面?我试过这个:
RedirectToAction("Index", "Dashboard"); // Goes to http://www.myexample.com/Dashboard
RedirectToRoute("MembersRoute", new {controller = Infrastructure.Member.GetAuthenticatedMembersUrl(), action = "Index"}); // Goes to http://www.myexample.com/Home/Index
我希望能够重定向到 http://www.example.com/Joes-Page
尝试
RedirectToAction("Index", "Dashboard", new { permalink = "Joes-Page"});
我在我的 MVC 站点中设置了自定义路由。不过,我无法弄清楚如何重定向到它。这是我的自定义路线代码:
public class MemberUrlConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
if (values[parameterName] != null)
{
var permalink = values[parameterName].ToString();
return string.Equals(permalink, Member.GetAuthenticatedMembersUrl(),
StringComparison.OrdinalIgnoreCase);
}
return false;
}
}
这是我的 RouteConfig.cs
文件:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "MembersRoute",
url: "{*permalink}",
defaults: new { controller = "Dashboard", action = "Index" },
constraints: new { permalink = new MemberUrlConstraint() });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
这工作正常。如果我在浏览器 URL 中输入类似 http://www.example.com/Joes-Page
的内容,它会正常工作。
我的问题是,如何以编程方式重定向到此页面?我试过这个:
RedirectToAction("Index", "Dashboard"); // Goes to http://www.myexample.com/Dashboard
RedirectToRoute("MembersRoute", new {controller = Infrastructure.Member.GetAuthenticatedMembersUrl(), action = "Index"}); // Goes to http://www.myexample.com/Home/Index
我希望能够重定向到 http://www.example.com/Joes-Page
尝试
RedirectToAction("Index", "Dashboard", new { permalink = "Joes-Page"});