在控制器.NET MVC中创建URL

Sco*_*hak 122 asp.net asp.net-mvc

我需要能够在控制器上的Action中构建一个链接来发送电子邮件.这样做的最佳做法是什么?我不希望自己构建它,以防我的路线发生变化.

我是否应该查看每封电子邮件并进行呈现并发送?这可能是一种很好的方式.

Gid*_*don 220

如果您只想获得某个操作的路径,请使用UrlHelper:

UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("About", "Home", null);
Run Code Online (Sandbox Code Playgroud)

如果要创建超链接:

string link = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Root", "About", "Home", null, null);
Run Code Online (Sandbox Code Playgroud)

Intellisense将为您提供每个参数的含义.


从评论更新:控制器已经有一个UrlHelper:

string url = this.Url.Action("About", "Home", null); 
Run Code Online (Sandbox Code Playgroud)

  • 后续:对于倒数第二个参数(RouteValueDictionary),这里有一个例子:new System.Web.Routing.RouteValueDictionary(new {id = 1}) (17认同)
  • 您不需要构建新的UrlHelper; 控制器上有一个.Url属性,它将为您提供一个具有正确RequestContext的属性. (15认同)
  • 您无需新建UrlHelper,只需访问Controller类中的Url属性即可. (3认同)

小智 22

如果您需要完整的URL(例如通过电子邮件发送),请考虑使用以下内置方法之一:

有了这个你修复de route用于build de url:

Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
Run Code Online (Sandbox Code Playgroud)

这里的url是在路由引擎确定de correct之后构建的:

Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
Run Code Online (Sandbox Code Playgroud)

在这两种方法中,最后2个参数指定协议和主机名.

问候.

  • 使用`Url.Action(action,controller,routevalue,protocol)`的FYI也会生成完整的URL,因此如果您不需要,则不必指定主机名. (7认同)

Mos*_*she 12

我有同样的问题,看来Gidon的答案有一个小缺陷:它产生一个相对的URL,不能通过邮件发送.

我的解决方案如下所示:

string link = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("ResetPassword", "Account", new { key = randomString });
Run Code Online (Sandbox Code Playgroud)

这样,生成了一个完整的URL,即使应用程序在托管服务器上有多个级别,并且使用80以外的端口,它也能正常工作.

编辑:我发现这也很有用.


Sph*_*xxx 7

另一种为操作创建绝对URL的方法:

var relativeUrl = Url.Action("MyAction");  //..or one of the other .Action() overloads
var currentUrl = Request.Url;

var absoluteUrl = new System.Uri(currentUrl, relativeUrl);
Run Code Online (Sandbox Code Playgroud)