Redirecting to a custom route in MVC

怎甘沉沦 提交于 2021-02-11 08:06:42

问题


I have setup a custom route in my MVC site. I am having trouble figuring out how to redirect to it though. Here is my custom route code:

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;
    }
}

Here is my RouteConfig.cs file:

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 }
        );
    }
}

This is working fine. If I put something like http://www.example.com/Joes-Page in my browser URL, it works fine.

My question is, how do I programmically redirect to this page? I've tried this:

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

I want to be able to redirect to http://www.example.com/Joes-Page


回答1:


Try

RedirectToAction("Index", "Dashboard", new { permalink = "Joes-Page"});


来源:https://stackoverflow.com/questions/40432201/redirecting-to-a-custom-route-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!