[英]Generate <a> link in controller to send in email
I'm implementing a password reset system, and while the code is working fine, there's a small problem... with the users. 我正在实施一个密码重置系统,并且在代码可以正常工作的同时,用户遇到了一个小问题。 The system works by generating single-use crypto-secure tokens which are sent via email. 该系统通过生成通过电子邮件发送的一次性使用的加密安全令牌来工作。 The problem is that to use these tokens, the user must then click on a link in the email they receive. 问题在于,要使用这些令牌,用户必须在收到的电子邮件中单击链接。 This in itself isn't a problem, but the link in question looks something like this: 这本身不是问题,但是有问题的链接看起来像这样:
http://www.example.com/Account/ResetPassword/184?t=BC2EveZtRl3wjbONboalzlUVwUpp%252BYaiKvbsZ6aPPYE%253D
The users are reluctant to click on this link because it's big and scary-looking; 用户不愿意单击此链接,因为它看起来又大又吓人。 they think it's a trick by some malicious third party to steal their password or give them a virus or something. 他们认为这是某些恶意第三方窃取密码或给他们提供病毒或某些东西的a俩。
If this was a view, I'd use @Html.ActionLink()
to generate a pretty <a>
link that said "Click here to reset your password", and that'd be fine. 如果是这样的话,我会使用@Html.ActionLink()
生成一个漂亮的<a>
链接,上面@Html.ActionLink()
“单击此处重置密码”,这样就可以了。 In a controller, however, I don't have access to that method unless I instantiate a HtmlHelper
, which requires ViewData
, which leads to a whole chain of things that need to be instantiated to fake up some stuff that I won't use anyway, and everywhere I've looked says that this is bad practice and I shouldn't do it. 但是,在控制器中,除非实例化一个HtmlHelper
,否则我将无法访问该方法,而HtmlHelper
需要ViewData
,这导致需要实例化整个事物链来伪造我不会使用的东西。 ,我到过的所有地方都说这是不好的做法,因此我不应该这样做。
What's the cleanest way to generate a neat <a>
link, in controller code, in ASP.NET MVC? 在ASP.NET MVC中以控制器代码生成整洁的<a>
链接的最简洁方法是什么?
The UrlHelper
is available in a controller via the Url
property, that can do the same thing, and that is to build a url for you. UrlHelper
可通过Url
属性在控制器中使用,它可以执行相同的操作,也就是为您构建一个url。 So you can feed your email sender a text that include a link and this is how you build that part of the email: 因此,您可以向电子邮件发送者提供包含链接的文本,这是您构建电子邮件的那部分的方法:
var link = "<a href='http://www.mysite.com/"
+ @Url.Action("ResetPassword","Account", new{id=184, t=token})
+"'>Click here to reset your password</a>"
// where token is your single-use crypto-secure
If you want the domain to be dynamic then you can change it to: 如果您希望域是动态的,则可以将其更改为:
var link = "<a href='"
+ Request.Url.Scheme + "://"
+ Request.Url.Authority
+ @Url.Action("ResetPassword","Account", new{id=184, t=token})
+"'>Click here to reset your password</a>"
// where token is your single-use crypto-secure
如果您使用的是Asp.NET Core 2.0或更高版本,则可以使用Url.Page()方法生成链接。
var link = Url.Page("/Account/ResetPassword", new{id=184, t=token}, Request.Scheme);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.