如何在 webmatrix 中将请求查询字符串转换为 HMACSHA256

How to convert request querystring to HMACSHA256 in webmatrix

以下代码在 webmatrix 中不起作用...(只有 kvps 部分不起作用)

@using System;
@using System.Collections.Generic;
@using System.Linq;
@using System.Web;
@using System.Configuration;
@using System.Text.RegularExpressions;
@using System.Collections.Specialized;
@using System.Security.Cryptography;
@using System.Text;
@using Newtonsoft.Json;

@{
    Func<string, bool, string> replaceChars = (string s, bool isKey) =>
    {
        string output = (s.Replace("%", "%25").Replace("&", "%26")) ?? "";

        if (isKey)
        {
            output = output.Replace("=", "%3D");
        }

        return output;
    };
//This part is not working...
    var kvps = Request.QueryString.Cast<string>()
    .Select(s => new { Key = replaceChars(s, true), Value = replaceChars(Request.QueryString[s], false) })
    .Where(kvp => kvp.Key != "signature" && kvp.Key != "hmac")
    .OrderBy(kvp => kvp.Key)
    .Select(kvp => "{kvp.Key}={kvp.Value}");

var hmacHasher = new HMACSHA256(Encoding.UTF8.GetBytes((string)AppState["secretKey"]));
var hash = hmacHasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("&", kvps)));
var calculatedSignature = BitConverter.ToString(hash).Replace("-", "");

}

相同的代码在 visual studio mvc 应用程序中运行良好。唯一的变化是 kvps 变量中的“$”符号...当在 webmatrix 中添加 $ 时,它会给出波浪形的红色下划线

var kvps = Request.QueryString.Cast<string>()
.Select(s => new { Key = replaceChars(s, true), Value = replaceChars(Request.QueryString[s], false) })
.Where(kvp => kvp.Key != "signature" && kvp.Key != "hmac")
.OrderBy(kvp => kvp.Key)
.Select(kvp => $"{kvp.Key}={kvp.Value}");

$ 是 C# 6.0 中的新增内容。它是用于字符串插值的运算符。所以,像这样:

$"{kvp.Key}={kvp.Value}"

表示将kvp.Keykvp.Value逐字替换为字符串中那些标识符的值。在较低版本的 C# 中,您需要执行以下操作:

String.Format("{0}={1}", kvp.Key, kvp.Value)