Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace response body using owin middleware

Tags:

.net

asp.net

owin

Is there a way to overwrite the response content using an OWIN middleware?

like image 982
ryudice Avatar asked Sep 23 '15 05:09

ryudice


1 Answers

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

enter image description here

like image 147
Florian SANTI Avatar answered Oct 04 '22 08:10

Florian SANTI