C# 在 MVC 中生成完整的 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10300833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate full URL in MVC?
提问by Banshee
Possible Duplicate:
How to I find the absolute url of an action in ASP.NET MVC?
Asp MVC Action link absolute url
Hi,
你好,
Is there a easy way to generate the full URL for a specific action? I have tried this :
是否有一种简单的方法可以为特定操作生成完整的 URL?我试过这个:
urlHelper.Action("Action", "Controller")
But this does generates a "\".
但这确实会生成一个“\”。
BestRegards
此致
Edit 1:I have tried this :
编辑1:我试过这个:
urlHelper.Action("List", "Ad", null, "http");
but it only returns : localhost:16055. I was expecting somthing like localhost:16055/Ad/List ?
但它只返回:localhost:16055。我期待像 localhost:16055/Ad/List 这样的东西?
采纳答案by Husein Roncevic
Use Html.ActionLink("Link Title", "Action", "Controller")
使用 Html.ActionLink("Link Title", "Action", "Controller")
To generate a full link use:
要生成完整链接,请使用:
@Html.ActionLink("Link Title", "Action", "Controller", "http", "www.mysampledomain.com",
"_blank", new {id = paramValue}, new { @class="someClass" })
That is the extension overload with all the parameters you can specify. Have a look at this MSDN article http://msdn.microsoft.com/en-us/library/dd492938.aspx
这是具有您可以指定的所有参数的扩展重载。看看这篇 MSDN 文章http://msdn.microsoft.com/en-us/library/dd492938.aspx
To generate from Controller use this code:
要从 Controller 生成,请使用以下代码:
var url = UrlHelper.GenerateUrl(null, "MyAction", "MyController", "http", "www.mydomain.com", String.Empty, null, RouteTable.Routes, this.ControllerContext.RequestContext, false);
url variable will contain a string representation of your URL. You can store it in ViewBag like:
url 变量将包含您的 URL 的字符串表示形式。您可以将其存储在 ViewBag 中,例如:
ViewBag.MyUrl = UrlHelper.GenerateUrl(null, "MyAction", "MyController", "http", "www.mydomain.com", String.Empty, null, RouteTable.Routes,
this.ControllerContext.RequestContext, false);
From View call it as:
从视图调用它为:
@ViewBag.MyUrl
That should be it.
应该是这样。
回答by Diego Dias
Url.action generates an url relative. To generate an url absolute you can look this: How do I find the absolute url of an action in ASP.NET MVC?
Url.action 生成一个相对的 url。要生成绝对网址,您可以查看:如何在 ASP.NET MVC 中找到操作的绝对网址?

