Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何找到控制器动作的绝对路径?_C#_Asp.net Mvc - Fatal编程技术网

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;
}