[英]How do I generate a URL outside of a controller in ASP.NET MVC?
How do I generate a URL pointing to a controller action from a helper method outside of the controller?如何从控制器外部的辅助方法生成指向控制器操作的 URL?
You could use the following if you have access to the HttpContext
:如果您有权访问
HttpContext
,则可以使用以下内容:
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
You can use LinkGenerator.您可以使用链接生成器。 It's new feature in Microsoft.AspNetCore.Routing namespace and has been added in Aug 2020.
它是 Microsoft.AspNetCore.Routing 命名空间中的新功能,已于 2020 年 8 月添加。
At first you have to inject that in your class:首先你必须在你的类中注入它:
public class Sampleervice
{
private readonly LinkGenerator _linkGenerator;
public Sampleervice (LinkGenerator linkGenerator)
{
_linkGenerator = linkGenerator;
}
public string GenerateLink()
{
return _linkGenerator.GetPathByAction("Privacy", "Home");
}
}
Using L01NL's answer, it might be important to note that Action method will also get current parameter if one is provided.使用 L01NL 的答案,重要的是要注意 Action 方法也将获得当前参数(如果提供的话)。 Eg:
例如:
editing project with id = 100 Url is http://hostname/Project/Edit/100
id = 100 的编辑项目 Url 是
http://hostname/Project/Edit/100
urlHelper.Action("Edit", "Project")
returns http://hostname/Project/Edit/100
urlHelper.Action("Edit", "Project")
返回http://hostname/Project/Edit/100
while urlHelper.Action("Edit", "Project", new { id = (int?) null });
while
urlHelper.Action("Edit", "Project", new { id = (int?) null });
returns http://hostname/Project/Edit
返回
http://hostname/Project/Edit
Since you probably want to use the method in a View, you should use the Url
property of the view.由于您可能想在视图中使用该方法,因此您应该使用视图的
Url
属性。 It is of type UrlHelper
, which allows you to do它是
UrlHelper
类型的,它允许你做
<%: Url.Action("TheAction", "TheController") %>
If you want to avoid that kind of string references in your views, you could write extension methods on UrlHelper
that creates it for you:如果你想避免在你的视图中使用这种字符串引用,你可以在
UrlHelper
上编写扩展方法来为你创建它:
public static class UrlHelperExtensions
{
public static string UrlToTheControllerAction(this UrlHelper helper)
{
return helper.Action("TheAction", "TheController");
}
}
which would be used like so:可以这样使用:
<%: Url.UrlToTheControllerTheAction() %>
Pass UrlHelper to your helper function and then you could do the following:将 UrlHelper 传递给您的辅助函数,然后您可以执行以下操作:
public SomeReturnType MyHelper(UrlHelper url, // your other parameters)
{
// Your other code
var myUrl = url.Action("action", "controller");
// code that consumes your url
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.