asp mvc 在控制器名称和路由中使用破折号?

发布于 2024-10-12 22:47:52 字数 492 浏览 2 评论 0原文

我有两个问题。我对 MVC 相当陌生,喜欢控制器和视图设置的新方式,但我不知道如何执行以下操作:

创建一个像 www.homepage.com/coming-soon 的 url

1)为此 url 类型正确的方法是什么?您是否创建一个名为 ComingSoonController 的控制器并以某种方式通过路由神奇地插入破折号?请注意,我不想要下划线,因为这不符合 SEO 的最佳利益。或者即将推出不在 URL 中的其他控制器上的某个操作名称并使用 [ActionName("name-with-dash")] 属性?

2) facebook、linkedin 和 twitter 的 URL 类似于 www.facebook.com/[个人资料名称]。在 MVC 中这将如何完成?显然[配置文件名称]是动态的。代码显然会存在于一个称为配置文件的控制器中。所以在我看来,你必须让 MVC 足够聪明,才能知道 URL 的第二部分何时是配置文件名称而不是控制器,并将其路由到配置文件控制器上的正确操作?这比听起来容易吗?

i have two questions. i'm fairly new to MVC and love the new way the controller and views are set up, but i can't figure out how to do the following:

1) make a url like www.homepage.com/coming-soon

for this type of url what is the right way to do it? do you create a controller named ComingSoonController and somehow magically insert a dash via routing? note i do NOT want underscores as that's not in the best interest of SEO. or is coming-soon some action name on some other controller that is not in the URL and use the [ActionName("name-with-dash")] attribute?

2) facebook, linkedin and twitter have urls like www.facebook.com/[profile name]. how would this be done in MVC? obviously the [profile name] is dynamic. and the code would obviously live in a controller called, say, profiles. so it seems to me that you would have to make MVC smart enough to know when that second part of the URL is a profile name and NOT a controller, and route it to the right action on the profiles controller? is this easier than it sounds?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

命硬 2024-10-19 22:47:52

1)这取决于coming-soon是否是动态部分。我假设是这样,并会建议这样的内容:

Global.asax

public static void RegisterRoutes(RouteCollection routes)
{
 routes.MapRoute(
                "Page", // Route name
                "{pageName}", // URL with parameters
                new { controller = "Home", action = "Page"} // Parameter defaults
             );

}

public class HomeController : Controller
{

 public ActionResult Page(string pageName)
 {
  return View();
 }
}

2)您可以按照上面所示的相同方式解决此问题,但请记住路线的顺序很重要。第一个匹配的获胜。如果您想要两个具有不同逻辑但相似 url 结构 www.mysite.com/coming-soon 和 www.mysite.com/{profile name} 的操作,假设第一个 url 具有静态部分,而后面的动态则可以执行类似的操作这个:

Global.asax

public static void RegisterRoutes(RouteCollection routes)
{
 routes.MapRoute(
                "Coming-soon", // Route name
                "coming-soon", // URL with parameters
                new { controller = "Home", action = "ComingSoon" } // Parameter defaults
             );

 routes.MapRoute(
                "Profiles", // Route name
                "{profileName}", // URL with parameters
                new { controller = "Home", action = "Profile"} // Parameter defaults
            );
}

public class HomeController : Controller
{
 public ActionResult ComingSoon()
 {
  return View();
 }

 public ActionResult Profile(string profileName)
 {
  return View();
 }

}

1) It depends if coming-soon is dynamic part or not. I'll presume it is and would suggest something like this:

Global.asax

public static void RegisterRoutes(RouteCollection routes)
{
 routes.MapRoute(
                "Page", // Route name
                "{pageName}", // URL with parameters
                new { controller = "Home", action = "Page"} // Parameter defaults
             );

}

public class HomeController : Controller
{

 public ActionResult Page(string pageName)
 {
  return View();
 }
}

2) You can resolve this same way as I've shown above, but keep in mind that order of routes is important. And that first one that matches wins. If you want two actions that have different logic but similar url structure www.mysite.com/coming-soon and www.mysite.com/{profile name}, presuming that first url has static part and the later dynamic you could do something like this:

Global.asax

public static void RegisterRoutes(RouteCollection routes)
{
 routes.MapRoute(
                "Coming-soon", // Route name
                "coming-soon", // URL with parameters
                new { controller = "Home", action = "ComingSoon" } // Parameter defaults
             );

 routes.MapRoute(
                "Profiles", // Route name
                "{profileName}", // URL with parameters
                new { controller = "Home", action = "Profile"} // Parameter defaults
            );
}

public class HomeController : Controller
{
 public ActionResult ComingSoon()
 {
  return View();
 }

 public ActionResult Profile(string profileName)
 {
  return View();
 }

}
凹づ凸ル 2024-10-19 22:47:52

您可以创建一个自定义路由处理程序,允许在网址中使用连字符:

创建一个新的处理程序

public class HyphenatedRouteHandler : MvcRouteHandler{
        protected override IHttpHandler  GetHttpHandler(RequestContext requestContext)
        {
            requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
            requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
            return base.GetHttpHandler(requestContext);
        }
    }

...以及新的路由:

routes.Add(
            new Route("{controller}/{action}/{id}", 
                new RouteValueDictionary(
                    new { controller = "Default", action = "Index", id = "" }),
                    new HyphenatedRouteHandler())
        );

MVC 带连字符的 url

You could create a custom route handler be allow hyphens in the urls:

Create a new handler

public class HyphenatedRouteHandler : MvcRouteHandler{
        protected override IHttpHandler  GetHttpHandler(RequestContext requestContext)
        {
            requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
            requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
            return base.GetHttpHandler(requestContext);
        }
    }

...and the new route:

routes.Add(
            new Route("{controller}/{action}/{id}", 
                new RouteValueDictionary(
                    new { controller = "Default", action = "Index", id = "" }),
                    new HyphenatedRouteHandler())
        );

MVC Hyphenated urls

千と千尋 2024-10-19 22:47:52

我为第一个问题开发了一个开源 NuGet 库,它将 EveryMvc/Url 隐式转换为 every-mvc/url。

虚线网址对 SEO 更友好且更易于阅读。 (更多内容请参阅我的博客文章

NuGet 包:https://www.nuget.org/packages/LowercaseDashedRoute/

要安装它,只需在 Visual Studio 中打开 NuGet 窗口即可右键单击该项目并选择 NuGet Package Manager,然后在“Online”选项卡上键入“Lowercase Dashed Route”,它应该会弹出。

或者,您可以在包管理器控制台中运行此代码:

Install-Package LowercaseDashedRoute

之后,您应该打开 App_Start/RouteConfig.cs 并注释掉现有的route.MapRoute(。 ..) 调用并添加以下内容:

routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
  new RouteValueDictionary(
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
    new DashedRouteHandler()
  )
);

就是这样。所有 url 均为小写、虚线,并且隐式转换,无需您执行任何其他操作。

开源项目网址:https://github.com/AtaS/lowercase-dashed-route

当涉及到第二个问题时,您可以通过创建自己的路由或使用自定义错误处理机制处理未找到的情况来做到这一点,但是如果您限制配置文件网址以符合某些规则(例如 don没有任何斜杠),这样您就可以更轻松地将其与其他 url 区分开来,例如内容文件 url,即 .css .js 等。

I've developed an open source NuGet library for the first problem which implicitly converts EveryMvc/Url to every-mvc/url.

Dashed urls are much more SEO friendly and easier to read. (More on my blog post)

NuGet Package: https://www.nuget.org/packages/LowercaseDashedRoute/

To install it, simply open the NuGet window in the Visual Studio by right clicking the Project and selecting NuGet Package Manager, and on the "Online" tab type "Lowercase Dashed Route", and it should pop up.

Alternatively, you can run this code in the Package Manager Console:

Install-Package LowercaseDashedRoute

After that you should open App_Start/RouteConfig.cs and comment out existing route.MapRoute(...) call and add this instead:

routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
  new RouteValueDictionary(
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
    new DashedRouteHandler()
  )
);

That's it. All the urls are lowercase, dashed, and converted implicitly without you doing anything more.

Open Source Project Url: https://github.com/AtaS/lowercase-dashed-route

When it comes to the second problem, you can do this either by making your own routes or handling not found with a custom error handling mechanism, but the routing will be faster if you restrict the profile urls to concur to some rules (like don't have any slashes) so that you can distinguish it from other urls much more easily, like from content file urls i.e. .css .js etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文