Jwt 如何使用自定义中间件获取响应体?
问题 如何使用自定义中间件在调用下一个上下文时获取响应体 到达wait_next行后,从调试调用(上下文) 不从操作结果getusermenu返回json数据Jwt 如何使用自定义中间件获取响应体?,jwt,asp.net-core-2.0,c#-7.0,jwt-auth,Jwt,Asp.net Core 2.0,C# 7.0,Jwt Auth,问题 如何使用自定义中间件在调用下一个上下文时获取响应体 到达wait_next行后,从调试调用(上下文) 不从操作结果getusermenu返回json数据 [HttpGet(Contracts.ApiRoutes.Security.GetUserMenus)] public IActionResult GetUserMenu(string userId) { string strUserMenus = _SecurityService.GetUser
[HttpGet(Contracts.ApiRoutes.Security.GetUserMenus)]
public IActionResult GetUserMenu(string userId)
{
string strUserMenus = _SecurityService.GetUserMenus(userId);
return Ok(strUserMenus);
}
我需要从上面的动作结果中得到反应体
header :
key : Authorization
value : ehhhheeedff .
我的代码我尝试过:
public async Task InvokeAsync(HttpContext context, DataContext dataContext)
{
// than you logic to validate token
if (!validKey)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Invalid Token");
}
//if valid than next middleware Invoke
else
{
await _next.Invoke(context);
// i need after that get result on last of thread meaning return data of usermenu
}
}
}
public static class TokenExtensions
{
public static IApplicationBuilder UseTokenAuth(this IApplicationBuilder builder)
{
return builder.UseMiddleware<TokenValidateMiddleware>();
}
}
[no return data from access token][1]
当令牌有效时,它会在浏览器googlechrom上返回如下数据
[
{
"form_name": "FrmAddPrograms",
"title": "Adding Screens",
"url": "",
"permissions": {
"Insert": "True",
"Edit": "True",
"Read": "True",
"Delete": "True",
"Print": "True",
"Excel": "False",
"RecordList": "False"
}
},
但在我的应用程序浏览器返回
无效令牌尝试使用以下代码在自定义中间件中获取响应正文:
public class CustomMiddleware
{
private readonly RequestDelegate next;
public CustomMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
if (!validKey)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Invalid Token");
}
//if valid than next middleware Invoke
else
{
Stream originalBody = context.Response.Body;
try
{
using (var memStream = new MemoryStream())
{
context.Response.Body = memStream;
await next(context);
memStream.Position = 0;
string responseBody = new StreamReader(memStream).ReadToEnd();//get response body here after next.Invoke()
memStream.Position = 0;
await memStream.CopyToAsync(originalBody);
}
}
finally
{
context.Response.Body = originalBody;
}
}
}
}
你期望得到什么样的回应?在请求委托上调用next只是将请求转发到行中的下一个中间件,或者在创建管道时请求到达ASP.NET Core提供的backstop处理程序,它将请求沿管道以另一个方向发回。forword请求到下一个Middleware行并显示响应正文感谢您的回复仍然在浏览器上返回无效令牌,尽管从调试到达isvalid=true,从调试获得字符串响应正文的值,如我所需,在邮递员上显示结果正确,但在浏览器中显示无效令牌消息此消息我写在代码上的无效令牌行上,但为什么显示此消息,尽管代码未命中无效token@ahmedabed elaziz您的意思是令牌有效,代码
等待context.Response.WriteAsync(“无效令牌”)代码>在添加断点时不会被点击,但浏览器会输出错误消息?令牌需要以承载xxxxx
开头。您是否在app.UseTokenAuth
之前添加app.UseMvc
?基于您没有令牌的代码,它运行良好,我认为这与您的令牌验证问题有关;app.UseHttpsRedirection();app.UseAuthentication();附录UseCors(“CorsData”);app.UseMvc();但是根据Bear的说法,我不想开始,因为我不知道你能告诉我我是如何使用app.class的中间件在app.usemvc之前有app.tokenauth但Bear不知道这方面的任何事情你能告诉我如何开始吗bearer@ahmedabed elaziz噢,忘了,如果您使用相同的令牌使用postman工作得很好…但是JWT身份验证本身将对令牌进行身份验证并返回结果,则无需编写自定义中间件。同样,它似乎与您的问题标题无关。您可以问一个新线程并发布必要的代码。
public class CustomMiddleware
{
private readonly RequestDelegate next;
public CustomMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
if (!validKey)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Invalid Token");
}
//if valid than next middleware Invoke
else
{
Stream originalBody = context.Response.Body;
try
{
using (var memStream = new MemoryStream())
{
context.Response.Body = memStream;
await next(context);
memStream.Position = 0;
string responseBody = new StreamReader(memStream).ReadToEnd();//get response body here after next.Invoke()
memStream.Position = 0;
await memStream.CopyToAsync(originalBody);
}
}
finally
{
context.Response.Body = originalBody;
}
}
}
}