重定向到MVC中的自定义路由 [英] Redirecting to a custom route in MVC

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

问题描述

我已经在我的MVC网站中设置了自定义路由.我在弄清楚如何重定向到它时遇到了麻烦.这是我的自定义路线代码:

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

这是我的 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 之类的字词,则效果很好.

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

我希望能够重定向到 http://www.example.com/Joes-Page

推荐答案

尝试

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

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

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