阅读响应流

时间:2019-02-01 12:14:40

标签: c# asp.net-web-api asp.net-core

我正在尝试在.NET Core 2.2中编辑响应正文。我能够成功读取请求正文,但无法读取响应正文。我尝试调用context.Request.EnableRewind();,然后再读取身体的流,但未成功。

我试图最后读取响应的正文,以便可以做与请求中相反的操作。是否有人对如何阅读响应正文有任何建议,以便我可以进行更改?这是在ASP .NET Core Web API中-我正在尝试使用中间件来修改响应主体。

我的代码如下

using (var bodyReader = new StreamReader(context.Request.Body))
{
    //Read the request body
    var bodyAsText = bodyReader.ReadToEnd();

    //Get the password for the private key
    var keyPass = _configuration["PrivateKeyPassword"];

    //Declare variable that will hold the key pair
    AsymmetricCipherKeyPair keyPair;

    //Read the keyPair from the private key
    using (var reader = File.OpenText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Keys\private.key")))
        keyPair = (AsymmetricCipherKeyPair)new PemReader(reader, new PasswordFinder(keyPass)).ReadObject();

    //Deserialize the JSON body into object
    // ReSharper disable once InconsistentNaming
    var e2eData = JsonConvert.DeserializeObject<E2EModel>(bodyAsText);

    //Create the decrypt engine to decrypt the data
    var decryptEngine = new Pkcs1Encoding(new RsaEngine());
    decryptEngine.Init(false, keyPair.Private);

    //Base64 Decode the key and IV
    var keyEncryptedBytes = Convert.FromBase64String(e2eData.Key);
    var ivEncryptedBytes = Convert.FromBase64String(e2eData.IV);

    //Decrypt the key and iv
    var key = decryptEngine.ProcessBlock(keyEncryptedBytes, 0, keyEncryptedBytes.Length);
    var iv = decryptEngine.ProcessBlock(ivEncryptedBytes, 0, ivEncryptedBytes.Length);

    //Convert the key and iv to string to trim it before use
    var keyStr = Encoding.UTF8.GetString(key).Trim();
    var ivStr = Encoding.UTF8.GetString(iv).Trim();

    string decryptedBody;

    //Decrypt the body with AES256 using key & IV derived above
    using (var aes = new AesManaged())
    {
        var decryptor = aes.CreateDecryptor(Encoding.UTF8.GetBytes(keyStr), Encoding.UTF8.GetBytes(ivStr));
        using (var memoryStream = new MemoryStream(Convert.FromBase64String(e2eData.Data)))
            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) 
                using (var reader = new StreamReader(cryptoStream))
                    decryptedBody = reader.ReadToEnd();
    }

    //Write the bytes into the memory stream
    injectedRequestStream.Write(Encoding.UTF8.GetBytes(decryptedBody), 0, decryptedBody.Length);
    //Set the seek to the begin on the stream
    injectedRequestStream.Seek(0, SeekOrigin.Begin);
    //Set the context request body to the new stream
    context.Request.Body = injectedRequestStream;
}

//Let the call through the remaining stack
await _next(context);

context.Request.EnableRewind();

var body = new StreamReader(context.Response.Body).ReadToEnd();

0 个答案:

没有答案