I’m trying to make an Attribute to Encrypt response of an Api.
This is the Attribute Code
public class MyCustomFilter : ActionFilterAttribute {
private MemoryStream responseBody;
public override void OnActionExecuting(ActionExecutingContext context) {
responseBody = new MemoryStream();
context.HttpContext.Response.Body = responseBody;
}
public override async void OnResultExecuted(ResultExecutedContext context) {
responseBody.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new(responseBody)) {
string actionResult = await sr.ReadToEndAsync();
string j = AesOperation.EncryptString("b14ca5898a4e4133bbce2ea2315a1916", actionResult);
Console.WriteLine("LLL");
Console.WriteLine(j);
context.HttpContext.Response.ContentType = "text/plain";
await context.HttpContext.Response.WriteAsync(j);
}
base.OnResultExecuted(context);
}
}
And This is The Api
[HttpGet]
[MyCustomFilter]
public ActionResult<GenericResponse<EnumDto>> Read() => repository.ReadAppSettings();
And Here is the Error I’m getting
Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HN5FN3JH41NQ", Request id "0HN5FN3JH41NQ:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: Response Content-Length mismatch: too few bytes written (0 of 12847).