我想知道是否可以从中间件向controllerAPI发送值?
例如,我想捕获一个特定的标题并发送给控制器。
类似的东西:
public class UserTokenValidatorsMiddleware
{
private readonly RequestDelegate _next;
//private IContactsRepository ContactsRepo { get; set; }
public UserTokenValidatorsMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Path.Value.Contains("auth"))
{
if (!context.Request.Headers.Keys.Contains("user-token"))
{
context.Response.StatusCode = 400; //Bad Request
await context.Response.WriteAsync("User token is missing");
return;
}
// Here I want send the header to all controller asked.
}
await _next.Invoke(context);
}
}
#region ExtensionMethod
public static class UserTokenValidatorsExtension
{
public static IApplicationBuilder ApplyUserTokenValidation(this IApplicationBuilder app)
{
app.UseMiddleware<UserTokenValidatorsMiddleware>();
return app;
}
}
#endregion
答案 0 :(得分:4)
我所做的是利用这些东西:
ActionFilterAttribute
(因为我可以访问IDependencyResolver)HierarchicalLifetimeManager
(因此我为每个请求获取一个新实例)(了解依赖范围)动作过滤器
public class TokenFetcherAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var token = actionContext.Request.Headers.Authorization.Parameter;
var scheme = actionContext.Request.Headers.Authorization.Scheme;
if (token == null || scheme != "Bearer")
return;
var tokenProvider = (TokenProvider) actionContext.Request.GetDependencyScope().GetService(typeof(TokenProvider));
tokenProvider.SetToken(token);
}
}
<强> TokenProvider 强>
public class TokenProvider
{
public string Token { get; private set; }
public void SetToken(string token)
{
if(Token != null)
throw new InvalidOperationException("Token is already set in this session.");
Token = token;
}
}
Unity配置
container.RegisterType<TokenProvider>(new HierarchicalLifetimeManager()); // Gets a new TokenProvider per request
<强>控制器强>
[TokenFetcher]
public class SomeController : ApiController
{
private TokenProvider tokenProvider;
// The token will not be set when ctor is called, but will be set before method is called.
private string Token => tokenProvider.Token;
public SomeController(TokenProvider provider)
{
tokeProvider = provider;
}
public string Get()
{
return $"Token is {Token}";
}
}
<强>更新强>
对于asp.net核心,使用内置DI容器。
将TokenProvider
注册为瞬态,以便为每个请求获取一个新的:
services.AddTransient<TokenProvider>();