如何在一个地方为所有控制器验证 Request.Headers[“Authorization"]? [英] How can I validate Request.Headers["Authorization"] for all controller at a single place?

查看:23
本文介绍了如何在一个地方为所有控制器验证 Request.Headers[“Authorization"]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[HttpGet]
public IActionResult Get()
{
    string token = Request.Headers["Authorization"];
    // Validate token.
}

[HttpPost]
public IActionResult Post(int id)
{
    string token = Request.Headers["Authorization"];
    // Validate token.
}

如何在一个地方为所有控制器验证 Request.Headers["Authorization"]?

How can I validate Request.Headers["Authorization"] for all controller at a single place?

推荐答案

您可以创建和使用自定义中间件,您可以在其中检查标头并验证是否应将其传递给控制器​​.

You can create and use custom middleware where you can check header and validate if it should be passed to controller or not.

为了实现创建中间件类并在 Startup.cs 中注册它,如下所示:

To achive that create middleware class and regiester it in Startup.cs as below:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConnectionManager conn, ILoggerFactory loggerFactory)
{
    app.UseMiddleware<YourMidllewareClass>();
}

在中间件类中创建 Invoke 方法.此方法将在每个请求跳转到您的任何控制器之前被调用.

Create Invoke method in middleware class. This method will get called before each request jump into any of your contoller.

public async Task Invoke(HttpContext context)
{
    string token = context.Request.Headers["Authorization"];

    //do the checking
    if (token == null)
    {
        context.Response.StatusCode = 401; 
        await context.Response.WriteAsync("Access denied!");
        return;
    }

    //pass request further if correct
    await _next(context);
}

据我所知,你必须在 UseMvc() 方法之前注册你的中间件,以确保你的 Invoke() 在 Mvc 管道之前被调用.

As far as I rember you must regiester your middleware before UseMvc() method to make sure your Invoke() will be called before Mvc pipeline.

这篇关于如何在一个地方为所有控制器验证 Request.Headers[“Authorization"]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆