Is there a way to overwrite the response content using an OWIN middleware?
My custom Error class
public class Error
{
public string error { get; set; }
public string description { get; set; }
public string url { get; set; }
}
My custom Middleware class
public class InvalidAuthenticationMiddleware : OwinMiddleware
{
public InvalidAuthenticationMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
var owinResponse = context.Response;
var owinResponseStream = owinResponse.Body;
var responseBuffer = new MemoryStream();
owinResponse.Body = responseBuffer;
await Next.Invoke(context);
var result = new Error
{
error = "unsupported_grant_type",
description = "The 'grant_type' parameter is missing or unsupported",
url = context.Request.Uri.ToString()
};
var customResponseBody = new StringContent(JsonConvert.SerializeObject(result));
var customResponseStream = await customResponseBody.ReadAsStreamAsync();
await customResponseStream.CopyToAsync(owinResponseStream);
owinResponse.ContentType = "application/json";
owinResponse.ContentLength = customResponseStream.Length;
owinResponse.Body = owinResponseStream;
}
}
registered in my Startup.cs
app.Use<InvalidAuthenticationMiddleware>();
I unselect the grant_type from the body to generate a 400 (bad request).
My answer in Postman
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With