如何在使用ApiController (ASP. js)时在API头中添加基本身份验证?. NET core / Bla



我想在api的头部添加一个基本的身份验证(询问用户名和密码)。我的类正在使用ApiController属性,并从ControllerBase继承。我只是不知道如何从这里向前走。

这是我目前为止写的:

[ApiController]
[Route("PDF/[controller]")]
public class ManagerPDF : ControllerBase
{
//Unrelated code
public ManagerPDF(Database DB, ManipulatorPDF manipulatorPDF)
{
//Unrelated code
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings_Authentication.json", optional: false, reloadOnChange: false).Build();
string username = config.GetSection("AuthenticationHeader")["username"];
string password = config.GetSection("AuthenticationHeader")["password"];
HttpContext.Request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{username}:{password}")));
}
//The requests
}

显示的代码片段是该类的控制器,JSON文件是存储用户名和密码的文件。我该如何从这里向前走?我知道它与添加请求和响应401请求有关,以检查用户名和密码是否正确,但我不确定如何添加它。或者我可能错了,它可能是完全不同的东西,但这是我的理解。

任何帮助将不胜感激!

要从头开始进行基本身份验证,可以参考https://www.codeguru.com/dotnet/authentication-asp-net/

如果你想在这里添加一个新的请求头。添加标题到httpcontext不会有帮助。httpcontext只是表示已经发生的进入ManagerPDF方法的请求。您需要在这里创建一个新请求来获取需要身份验证以获取数据的其他api。你不应该在这里使用ManagerPDF作为方法名。控制器类的同名用于构造函数,如注入httpclient。

public class ManagerPDF : ControllerBase
{
private readonly HttpClient _client;
public ManagerPDF(HttpClient client)
{
this._client = client;
}
public ManagerPDF1(Database DB, ManipulatorPDF manipulatorPDF)
{
//Unrelated code
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings_Authentication.json", optional: false, reloadOnChange: false).Build();
string username = config.GetSection("AuthenticationHeader")["username"];
string password = config.GetSection("AuthenticationHeader")["password"];
var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7171/identity");  //other api you want to request
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{username}:{password}")));
var response = await _client.SendAsync(request);  //then you can use the content you requested.
if (response.IsSuccessStatusCode)
{
content = await response.Content.ReadAsStringAsync();
}
}       
}