使用OWIN中间件替换响应主体 [英] Replace response body using owin middleware
本文介绍了使用OWIN中间件替换响应主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用OWIN中间件覆盖响应内容?
Is there a way to overwrite the response content using an OWIN middleware?
推荐答案
我的自定义错误类
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中注册
registered in my Startup.cs
app.Use<InvalidAuthenticationMiddleware>();
我从正文中取消选择grant_type以生成400(错误请求).
I unselect the grant_type from the body to generate a 400 (bad request).
我在邮递员中的答案
这篇关于使用OWIN中间件替换响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文