ryudice
ryudice

Reputation: 37406

Replace response body using owin middleware

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

Upvotes: 6

Views: 3477

Answers (1)

Florian SANTI
Florian SANTI

Reputation: 551

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

Upvotes: 6

Related Questions