Razor 引擎:URL 在模板中生成 & 生成 &

Razor Engine: URL generation in template of & generates &

我有一个 ASP.NET 核心应用程序,它使用 Identity 进行用户管理。

我有一个 MailProvider 准备通过 smtp 发送电子邮件以激活帐户:

// ...
var activationMailViewModel = new ActivationMailViewModel()
{
    LastName = user.LastName,
    FirstName= user.FirstName,
    UserName = userName,
    Email = user.Email,
    CompanyName = companyName,
    Url = url.Action("ConfirmEmail", "Account", new { Area = "", code = token, userId = user.Id }, request.Scheme)
};
// ...
var result = Engine.Razor.RunCompile(new LoadedTemplateSource($"Activation", path), "SendUserAccountCreation" + Guid.NewGuid(), null, activationMailViewModel);
// ...

 var mailMessage = new MailMessage(
                new MailAddress("kyc@vente-privee.com", "KYC-vente-privee.com"),
                new MailAddress(user.Email, userName))
            {
                Subject = GetGlobalString("ActivationMail_Subject", cultureCode),
                BodyEncoding = System.Text.Encoding.UTF8,
                SubjectEncoding = System.Text.Encoding.UTF8
            };

<p><a href="@Model.Url" class="button">ACTIVATE MY ACCOUNT</a></p>

然而,由于在 [=55] 的查询字符串中将字符 & 转录为 &amp;,生成的 link 似乎可以用两种不同的方式解释=].

http://base.url.net/Account/ConfirmEmail?code=CfDJ8PtYvJr8Ve1GnxXJykedIzKTQDg%2FTXBwV6NmIYMy8Gi7yUbqZagGbZRacKSFrE717h%2FGjmm6l8QA3knPPgxyNnM1vxe3wb6KnFsGtZUOMTas7QhX1MW5dE4cU5sorA99Dz03zV8ldVMOMP5BGfUrts2nNQqbs8dNLPNgupdkNzaWa4q6fM5u9E99CzRcFjAn7nnd57Ht3IIREAqz6lqufFYo469%2BN2VJxmNJJ1p6OAvO6dMJ9M%2Fzdz3xkpBajJbxRw%3D%3D**&**userId=21e4673c-f121-417f-9837-7f5b234f6f01

http://base.url.net/Account/ConfirmEmail?code=CfDJ8PtYvJr8Ve1GnxXJykedIzKTQDg%2FTXBwV6NmIYMy8Gi7yUbqZagGbZRacKSFrE717h%2FGjmm6l8QA3knPPgxyNnM1vxe3wb6KnFsGtZUOMTas7QhX1MW5dE4cU5sorA99Dz03zV8ldVMOMP5BGfUrts2nNQqbs8dNLPNgupdkNzaWa4q6fM5u9E99CzRcFjAn7nnd57Ht3IIREAqz6lqufFYo469%2BN2VJxmNJJ1p6OAvO6dMJ9M%2Fzdz3xkpBajJbxRw%3D%3D**&**userId=21e4673c-f121-417f-9837-7f5b234f6f01

这对 my AccountController:

可能有问题
[Authorize]
public class AccountController : BaseController
{

    // GET: /Account/ConfirmEmail
    [AllowAnonymous]
    public async Task<ActionResult> ConfirmEmail(string code, string userId)
    {
        if (code == null || userId == null)
        {
            return View("Error");
        }

    // Rest of the code... not relevant to the question
}

如果浏览器/邮件客户端将&解释为&amp;,那么userId将被设置为null并且无法确认帐户/电子邮件。

例如:

然而,在两个电子邮件提供商中,纯文本显示 url 是使用 Razor 引擎生成的:&amp;.

最好的策略是什么,这样我的用户就不会得到一个不起作用的 link。

问题似乎与未应用于电子邮件的原始格式有关。

给出的答案

When doing e-mails, I use the RazorEngineService in RazorEngine.Templating, e.g. in my case, it looks like this:

using RazorEngine.Templating;

RazorEngineService.Create().RunCompile(html, ...) 

Assuming you are using the same assembly, @Html.Raw does NOT exist with this usage. I > was finally able to get raw HTML output by doing this in my e-mails:

@using RazorEngine.Text

@(new RawString(Model.Variable))