【发布时间】:2020-03-23 14:19:15
【问题描述】:
我的基础Request 类如下所示:
public class GetAllProjectsQuery : QueryBase<ProjectsListModel>
{
}
public abstract class QueryBase<T> : UserContext, IRequest<T> // IRequest is MediatR interface
{
}
public abstract class UserContext
{
public string ApplicationUserId { get; set; } // and other properties
}
我想为我的.NET Core 3.1 WebApi 编写一个中间件,它将从请求头中获取JWT 并从中读取ApplicationUserId。我开始编写代码:
public class UserInformation
{
private readonly RequestDelegate next;
public UserInformation(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var jwt = context.Request.Headers["Authorization"];
// read jwt here
var userContext = (UserContext)context.Request.Body; // i know it wont work
userContext.ApplicationUserId = //whats next? Any ideas?
await this.next(context);
}
}
但老实说,我不知道如何开始,所以这是我的问题:
如您所见,每个请求都将包含我的UserContext 类等等。如何将HttpContext.Request.Body 转换为我的请求对象并将ApplicationUserId 附加到它?可能吗?我想从我的 JWT 从标头访问用户凭据,并且我希望在我的 API 中的每个请求中都有该信息(将其传递给控制器,然后传递给命令等)。
如果从中间件获取这些信息不是最佳做法,那是什么?
编辑:使用MediatR的Mcontroller:
// base controller:
[ApiController]
[Route("[controller]")]
public abstract class BaseController : ControllerBase
{
private IMediator mediator;
protected IMediator Mediator => this.mediator ?? (this.mediator = HttpContext.RequestServices.GetService<IMediator>());
}
// action in ProjectControlle
[HttpGet]
[Authorize]
public async Task<ActionResult<ProjectsListModel>> GetAllProjects()
{
return Ok(await base.Mediator.Send(new GetAllProjectsQuery()));
}
// query:
public class GetAllProjectsQuery : QueryBase<ProjectsListModel>
{
}
// handler:
public class GetAllProjectsQueryHandler : IRequestHandler<GetAllProjectsQuery, ProjectsListModel>
{
private readonly IProjectRepository projectRepository;
public GetAllProjectsQueryHandler(IProjectRepository projectRepository)
{
this.projectRepository = projectRepository;
}
public async Task<ProjectsListModel> Handle(GetAllProjectsQuery request, CancellationToken cancellationToken)
{
var projects = await this.projectRepository.GetAllProjectsWithTasksAsync();
return new ProjectsListModel
{
List = projects
};
}
}
【问题讨论】:
-
看看this的帖子。
标签: c# asp.net-core