受欢迎的博客标签

加密解密传输中间件 asp .net core

Published

 .NETCore 下的 Middleware

// .NET Core 版本
public class SecuriryTransportMiddleware {
    private readonly RequestDelegate _next;

    public RequestCultureMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    
    public async Task InvokeAsync(HttpContext context)
    {
    	// request handle
        var encryptedBody = context.Request.Body;
        var encryptedContent = new StreamReader(encryptedBody).ReadToEnd();
        var decryptedBody = RsaHelper.Decrypt(privateKey, encryptedContent);
        var originBody = JsonHelper.Deserialize<object>(decryptedBody);
        
        var json = JsonHelper.Serialize(dataSource);
        var requestContent = new StringContent(json, Encoding.UTF8, "application/json");
        stream = await requestContent.ReadAsStreamAsync();
        context.Request.Body = stream;
        
        await _next(context);
        // response handle
        var originContent = new StreamReader(context.Response.Body).ReadToEnd();
        var encryptedBody = RsaHelper.Encrypt(privateKey, originContent);
        var responseContent = new StringContent(json, Encoding.UTF8, "application/json");
        context.Response.Body = await responseContent.ReadAsStreamAsync();
        // 或者直接
        // await context.Response.WriteAsync(encryptedBody);
    }
}

 

 

 

https://www.cnblogs.com/ms27946/p/Transmission-Encryption-In-Net-WebApi.html