使用owin中间件替换响应主体

时间:2015-09-23 05:35:18

标签: asp.net .net owin

有没有办法使用OWIN中间件覆盖响应内容?

1 个答案:

答案 0 :(得分:1)

我的自定义错误类

public class Error
{
    public string error { get; set; }
    public string description { get; set; }
    public string url { get; set; }
}

我的自定义中间件类

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;
    }
}

在我的Startup.cs中注册

app.Use<InvalidAuthenticationMiddleware>();

我从正文中取消选择grant_type以生成400(错误请求)。

我在邮递员中的答案

enter image description here