有没有办法使用OWIN中间件覆盖响应内容?
答案 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(错误请求)。
我在邮递员中的答案