如何强制MVC路由到首页/指数,而不是根源在哪里? [英] How to force MVC to route to Home/Index instead of root?

查看:135
本文介绍了如何强制MVC路由到首页/指数,而不是根源在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个MVC动作或操作链接,例如 @ Url.Action(指数,家),我重定向到的 http://www.example.com ,但我要的是迫使它重定向到的 http://www.example.com/Home/Index HTTP://www.example .COM /家庭。有没有办法来明确渲染的完整路径?我的谷歌搜索都上来了空。

If I create an MVC action or action link, e.g. @Url.Action("Index", "Home")" I get redirected to http://www.example.com, but what I want is to force it to redirect to http://www.example.com/Home/Index or http://www.example.com/Home. Is there a way to explicitly render the full path? My Google searches are coming up empty.

推荐答案

Url.Action() 使用路由来生成URL。所以,如果你想改变它,你必须改变这种状况。目前,它说的默认控制器是首页键,默认操作是首页。其更改为别的,然后它应该给你一个不同的URL。

Url.Action() uses the routing to generate the URL. so if you want to change it, you must change that. It currently says the default controller is Home and default action is Index. Change them to anything else and it should then give you a different URL.

例如您的路由配置大概是这样的:

For example your route configuration is probably something like this:

 routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
 );

更改默认为任何东西或删除:

Change the defaults to anything else or remove them:

 routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { id = UrlParameter.Optional }
 );

请注意,这样做,这意味着您的网页将只能由全控制器/动作路径来访问,所以你可能要创建一个登陆页面,并做出了默认值。

Note that doing this means your pages will only be accessible by full controller/action paths so you may want to create a landing page and make that the default.

如果你绝对需要知道一个动作的完整URL,那么你可以这样来做。首先创建一个额外的途径,并把它放在你的路线配置的底部。这将永远不会使用的系统默认为:

If you absolutely need to know the full URL of an action then you can do it this way. first create an additional route and put it at the bottom of your route config. This will never get used by the system by default:

routes.MapRoute(
    name: "AbsoluteRoute",
    url: "{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional }
);

然后在code你可以调用这个(不知道它在剃刀可用,但它应该是容易写一个辅助方法):

Then in code you can call this (not sure it's available in Razor, but it should be easy to write a helper method):

var fullURL = UrlHelper.GenerateUrl("AbsoluteRoute", "Index", "Home", null, null, null, null, System.Web.Routing.RouteTable.Routes, Request.RequestContext, false);

这篇关于如何强制MVC路由到首页/指数,而不是根源在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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