Is there a way to overwrite the response content using an OWIN middleware?
Asked
Active
Viewed 3,260 times
6
-
you have access to the `response` object inside your `middleware`.I think it should be possible. – Amit Kumar Ghosh Sep 23 '15 at 06:31
-
you can find example in my answer here http://stackoverflow.com/questions/32676616/why-mvc-handler-didnt-execute-after-iappbuilder-run-method-invoked/32680502#32680502 – Anton Putau Sep 23 '15 at 12:48
1 Answers
6
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

Florian SANTI
- 531
- 1
- 5
- 13