我正在研究 ASP.NET Core 2.0 RESTful API。我有一个场景,我需要使用 HTTPGet 方法来调用 API Controller 上的操作,并且需要提取将用于调用另一个 3rd 方 API 的用户名和密码值。用户名和密码与当前登录的用户身份无关,它们只是我想从我自己的 API 中发送到另一个 API 的值,但我不想只是在查询字符串中传递它们。
我可以在客户端使用基本身份验证将用户名和密码添加到 HttpRequestMessage 身份验证 header ,然后在我的 ASP.NET Core 2.0 API Controller 操作中提取该 header 吗?
我的客户在调用 API 的代码中会有类似的内容
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, relativeUrl);
var byteArray = new UTF8Encoding().GetBytes(string.Format($"username:password"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
并且,我的 API Controller 操作将开始这样的操作;
[HttpGet()]
public IActionResult GetUploadedFileList([FromQuery]int pageNumber, [FromQuery]int pageSize)
{
//Extract Authentication header values for username and password
}
谁能提供一个如何从 HTTPGet 请求中获取 Authorization header 的示例
我意识到我可以使用 HTTPPost [FromBody] 轻松完成此操作,但我的用例要求此方法为 HTTGet。
在此先感谢您的帮助。
编辑 1 - 解决方案
多亏了来自 this link 的一些提示,我才能使下面的代码正常工作.尽管这看起来需要做很多工作,但如果有人有更好或更简洁的解决方案,请发布您的示例。
[HttpGet()]
public IActionResult GetUploadedFiles([FromQuery]int pageNumber, [FromQuery]int pageSize)
{
string username = string.Empty;
string password = string.Empty;
if (Request.Headers.TryGetValue("Authorization", out StringValues authToken))
{
string authHeader = authToken.First();
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':');
username = usernamePassword.Substring(0, seperatorIndex);
password = usernamePassword.Substring(seperatorIndex + 1);
}
else
{
return BadRequest("Missing Authorization Header.");
}
//Build FilesUploadedListRequest
FilesUploadedListRequest filesUploadedListRequest = new FilesUploadedListRequest
{
Username = username,
Password = password,
PageNumber = pageNumber,
PageSize = pageSize
};
//Call GetUploadedFilesList
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;
Task<FilesUploadedListResponse> FilesUploadedListResponse = _clientService.GetListOfUploadedFilesAsync(filesUploadedListRequest, cancellationToken);
//Return results
if (filesUploadedListResponse.Result.Success)
{
return Ok(filesUploadedListResponse.Result);
}
return StatusCode(filesUploadedListResponse.Result.StatusCode, filesUploadedListResponse.Result.Reason);
}
最佳答案
ASP.NET Core 支持 [FromHeader]
Action 参数的属性,类似于 [FromBody]
和 [FromQuery]
.所以添加一个 [FromHeader]string authorization
arg 到您的操作将使您的解决方案减少几行,并使该方法更具可测试性,因为您可以避免访问 Request
目的。
关于c# - 如何从发送到 ASP.NET 核心 2.0 API Controller 操作的请求中获取身份验证 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123856/