是否可以从aspnet核心api中的中间件向控制器发送值?

时间:2016-08-18 11:55:41

标签: .net asp.net-web-api http-headers asp.net-core middleware

我想知道是否可以从中间件向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 

1 个答案:

答案 0 :(得分:4)

我所做的是利用这些东西:

  • 依赖注入(Unity)
  • 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>();