0

下面的代码在 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}");
4

1 回答 1

1

$是 C# 6.0 中的新功能。它是字符串插值的运算符。所以,像:

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

意思是用字符串中那些标识符的值逐字替换kvp.Key和。kvp.Value在较小版本的 C# 中,您需要执行以下操作:

String.Format("{0}={1}", kvp.Key, kvp.Value)
于 2017-05-11T19:05:41.627 回答