URL中没有控制器或动作名称的ASP.NET MVC路由 [英] ASP.NET MVC routing without controller or action name in URL

查看:132
本文介绍了URL中没有控制器或动作名称的ASP.NET MVC路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的URL结构类似于 http://website.com/city-state/category 例如/miami-fl/restaurants或/los-angeles-ca/bars.为了将其发送到正确的控制器,我有一个从RouteBase派生的类,该类拆分请求路径并弄清楚城市,州和类别.这对于传入的URL很好.

My URL structure is like http://website.com/city-state/category e.g. /miami-fl/restaurants or /los-angeles-ca/bars. In order to send it to the correct controller, I have a class derived from RouteBase, which splits the request path and figures out the city, state and category. This is working fine for incoming URLs.

public class LegacyUrlRoute : RouteBase
{

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        RouteData routeData = new RouteData();
        routeData.RouteHandler = new MvcRouteHandler();

        string url = httpContext.Request.Path.ToLower(); //e.g. url = /los-angeles
        string[] path = url.TrimStart('/').Split('/'); //
        if (path.Length > 1)
        {
            string[] locale = path[0].Split('-');
            if (locale.Length > 1) //This is a city page, so send it to category controller
            {
                string stateName = locale[locale.Length - 1];
                string cityName = path[0].Replace(stateName, "").TrimEnd('-');

                routeData.Values.Add("controller", "Category");
                routeData.Values.Add("action", "City");
                routeData.Values.Add("categoryname", path[1]);
                routeData.Values.Add("city", cityName);
                routeData.Values.Add("state", stateName);
            }
        }
    }
}

但是,当我尝试使用Html.ActionLink创建链接时,它不会从此类中拾取.

However, when I try to use Html.ActionLink to create a link, it doesn't pick up from this class.

@Html.ActionLink("Restaurants in Miami", "Index", "Category", new {categoryname="Restaurants", state="FL", city="Miami"})

给我一​​个/category/index?categoryname = restaurants& state = fl& city = miami的网址. 如何为我的URL结构生成准确的链接.

gives me a url of /category/index?categoryname=restaurants&state=fl&city=miami. How do I generate accurate links for my URL structure.

推荐答案

如果您希望外发URL起作用,则必须实现GetVirtualPath,它将一组路由值转换为URL.它通常应该是您的GetRouteData方法的镜像.

If you want your outgoing URLs to function, you must implement GetVirtualPath, which converts a set of route values into a URL. It should typically be the mirror image of your GetRouteData method.

最简单的实现方法是创建一个将路由值映射到URL的数据结构,然后在两种方法中都使用它,如

The simplest way to implement it would just be to make a data structure that maps your route values to URLs and then use it in both methods as in this example.

这篇关于URL中没有控制器或动作名称的ASP.NET MVC路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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