C# 如何找到控制器动作的绝对路径?
我需要生成一个链接到一个行动,并发送电子邮件的链接。我想这样称呼:C# 如何找到控制器动作的绝对路径?,c#,asp.net-mvc,C#,Asp.net Mvc,我需要生成一个链接到一个行动,并发送电子邮件的链接。我想这样称呼: public string GetAbsolutePath(string actionName, string controllerName, string id) { // Somehow generate the absolute path } public string GetAbsolutePath(string actionName, string controllerName, string id) {
public string GetAbsolutePath(string actionName, string controllerName, string id)
{
// Somehow generate the absolute path
}
public string GetAbsolutePath(string actionName, string controllerName, string id)
{
var relUrl = Url.RouteUrl(new { controller = controllerName, action = actionName, id = id });
return Request.Url.GetLeftPart(UriPartial.Authority).TrimEnd('/') + relUrl;
}
我想我可以使用virtualPath.ToAbsolute(字符串virtualPath),但我也不确定如何获得虚拟路径。您可以使用路由机制为您生成链接。有几种方法可以做到这一点,例如,在视图中,您可以使用
<%= Url.Action(actionName, controllerName, new {id=id} %>
类似这样的内容:
public string GetAbsolutePath(string actionName, string controllerName, string id)
{
// Somehow generate the absolute path
}
public string GetAbsolutePath(string actionName, string controllerName, string id)
{
var relUrl = Url.RouteUrl(new { controller = controllerName, action = actionName, id = id });
return Request.Url.GetLeftPart(UriPartial.Authority).TrimEnd('/') + relUrl;
}
在给定控制器和操作的情况下,可以使用路由引擎为您生成路由。控制器的RouteCollection属性可按如下方式使用:
string virtualPath =
RouteCollection.GetVirtualPath(context, new {
action = actionName,
controller = controllerName,
id = id
}
).VirtualPath;
string url = VirtualPathUtility.ToAbsolute(virtualPath);
我的结局是:
public static string AbsoluteAction(this UrlHelper url, string action, string controller, object routeValues)
{
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
string absoluteAction = string.Format("{0}://{1}{2}",
requestUrl.Scheme,
requestUrl.Authority,
url.Action(action, controller, routeValues, null));
return absoluteAction;
}