1.方法一 (HttpContext.Items)
获取
中间件
public class MySuperAmazingMiddleware { private readonly RequestDelegate _next; public MySuperAmazingMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext context) { var mySuperAmazingObject = GetSuperAmazingObject(); context.Items.Add("SuperAmazingObject", mySuperAmazingObject ); // Call the next delegate/middleware in the pipeline return this._next(context); } }
获取
var mySuperAmazingObject = (SuperAmazingObject)HttpContext.Items["mySuperAmazingObject"];
2.方法二 (HttpContext.User)
public class SampleActionFilter : IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "test") }, "Basic"); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); context.HttpContext.User = claimsPrincipal; await next(); } }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add<SampleActionFilter>(); }); }
public class HomeController : Controller { public IActionResult Index() { return Content("Current User: " + User.Identity.Name ); } }