I have an asp.net mvc app and want to compress body of the request in the view with Pako library (using gzip and deflate encoding) and decompress the body request before arriving to the controller using OnActionExecuting and GZipStream/DeflateStream.
why want to do that ? because I have a firewall that block all request > 128KB so I compress if necessary, I already do that with another app in angular 10 and .NET Core API, but can't do the same thing in asp.net mvc :(
for now I can compress the body and send it with ajax to the controller, OnActionExecuting is triggred but my code don't work request.Filtrer pass but I have null in the model controller and filterContext.ActionParameters.Values is null too.
I achived this with angular 10 and API.NET Core and it work I used pako in angular and this code in my api core :
public async Task Invoke(HttpContext httpContext)
{
await SlowStuffSemaphore.WaitAsync();
try
{
_httpContext = httpContext;
bool isGzip = IsGzipRequest();
if (isGzip)
{
_httpContext.Request.Body = new GZipStream(_httpContext.Request.Body, CompressionMode.Decompress);
}
await _next.Invoke(_httpContext);
}
catch(ArgumentNullException e)
{
Console.WriteLine("Error: " + e.Message);
}
finally
{
SlowStuffSemaphore.Release();
}
}
my ASP.NET MVC Code :
View :
<script>
window.SendZipedRequest = (reqbody) => {
$.ajax({
url: "/Home/AddAgency",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
type: "post",
headers: { "Content-Encoding": "gzip" },
data: pako.gzip(JSON.stringify(reqbody), {to: "string"}),
beforeSend: function (data) {
//Do Something
},
success: function (data, textStatus, jqXHR) {
console.log('Yay!');
//$("#content").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Oh no!');
},
complete: function (jqXHR, textStatus) {
console.log(textStatus);
console.log(jqXHR.status);
//console.log(jqXHR.responseText);
}
});
}
</script>
ActionFilterAttribute:
public class CompressContentAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
request.Filter = new GZipStream(request.Filter, CompressionMode.Decompress);
base.OnActionExecuting(filterContext);
}
}
another problem I have it's HttpContext.Request.InputStream (stream contain my body) it's readonly
thanks