Чтение потока ответов - PullRequest
       6

Чтение потока ответов

0 голосов
/ 01 февраля 2019

Я пытаюсь отредактировать тело ответа в .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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...