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

查看:38
本文介绍了如何在单个位置为所有控制器验证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方法.在每个请求跳转到您的任何contoller中之前,都会调用此方法.

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()方法之前重新注册中间件,以确保在Mvc管道之前调用Invoke().

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天全站免登陆