MVC中的URL编码令牌

时间:2019-02-22 15:52:03

标签: c# .net .net-core

Core 2 MVC。我想生成“确认电子邮件链接”。我生成这样的令牌:

var token = await m_userManager.GenerateEmailConfirmationTokenAsync(user);

向用户发送电子邮件以激活他/她的帐户。但是通过的令牌已从输入中删除了“ +”:

    // Original
CfDJ8ON8hfMagqZNkicGHBXln5hi6kj4TCMMaxS5SaaU4BzEgFlKev1mT2gsij7gh2AkG8G+00t4n/PGwX6oQCvnpHk+wIGc1y8ycNbnzGpwW9Q8fwRlZDGQcIMtSCmX7LXwRS0iHSXgDF1O/QcDNGKbIMMZdcfMKYwnnzmUpmNxvZtG0JCYu5o754Y83VEtdbKASlzQz4aFxOUulvHRBQc3xRi2r0N8yveg26FO+RJ9khsqxKGRu4JDDVNWkpguXeVJvA==

    //Notice '+' is missin
CfDJ8ON8hfMagqZNkicGHBXln5hi6kj4TCMMaxS5SaaU4BzEgFlKev1mT2gsij7gh2AkG8G 00t4n/PGwX6oQCvnpHk wIGc1y8ycNbnzGpwW9Q8fwRlZDGQcIMtSCmX7LXwRS0iHSXgDF1O/QcDNGKbIMMZdcfMKYwnnzmUpmNxvZtG0JCYu5o754Y83VEtdbKASlzQz4aFxOUulvHRBQc3xRi2r0N8yveg26FO RJ9khsqxKGRu4JDDVNWkpguXeVJvA==

控制器:

[HttpGet]
public async Task<IActionResult> Activate(Guid? id, string token)
{
       ...

这里的解决方案是什么?我应该简单地用+符号代替“空格”吗?

1 个答案:

答案 0 :(得分:3)

您可以对令牌进行编码,然后在收到令牌时进行解码。这样可以避免url编码。

示例:

public static void Main()
{
    var token = "CfDJ8ON8hfMagqZNkicGHBXln5hi6kj4TCMMaxS5SaaU4BzEgFlKev1mT2gsij7gh2AkG8G+00t4n/PGwX6oQCvnpHk+wIGc1y8ycNbnzGpwW9Q8fwRlZDGQcIMtSCmX7LXwRS0iHSXgDF1O/QcDNGKbIMMZdcfMKYwnnzmUpmNxvZtG0JCYu5o754Y83VEtdbKASlzQz4aFxOUulvHRBQc3xRi2r0N8yveg26FO+RJ9khsqxKGRu4JDDVNWkpguXeVJvA==";
    var newToken = HttpUtility.UrlEncode(token);
    Console.WriteLine(newToken);
    //this will print newToken without +
    var originalToken = HttpUtility.UrlDecode(newToken);
    //this will print original token, with +
    Console.WriteLine(originalToken);
}