Sha*_*ean 32 c# asp.net-mvc controller html-helper asp.net-mvc-3
如何从控制器外部的辅助方法生成指向控制器操作的URL?
L01*_*1NL 81
如果您有权访问以下内容,则可以使用以下内容HttpContext:
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
Run Code Online (Sandbox Code Playgroud)
您可以使用 LinkGenerator 。它是 Microsoft.AspNetCore.Routing 命名空间中的新功能,于 2020 年 8 月添加。
首先你必须将其注入到你的类中:
public class Sampleervice
{
private readonly LinkGenerator _linkGenerator;
public Sampleervice (LinkGenerator linkGenerator)
{
_linkGenerator = linkGenerator;
}
public string GenerateLink()
{
return _linkGenerator.GetPathByAction("Privacy", "Home");
}
}
Run Code Online (Sandbox Code Playgroud)
欲了解更多信息,请查看此
Mah*_*aga -5
将 UrlHelper 传递给您的辅助函数,然后您可以执行以下操作:
public SomeReturnType MyHelper(UrlHelper url, // your other parameters)
{
// Your other code
var myUrl = url.Action("action", "controller");
// code that consumes your url
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23290 次 |
| 最近记录: |