如何从发送到ASP.NET核心2.0 API控制器操作的请求中获取身份验证标头

EiE*_*Guy 1 http-headers dotnet-httpclient asp.net-apicontroller asp.net-core-2.0

我正在开发ASP.NET Core 2.0 RESTful API.我有一个场景,我需要使用HTTPGet方法在我的API控制器上调用操作,我需要提取用于调用另一个第三方API的用户名和密码值.用户名和密码与当前登录的用户标识无关,它们只是我想从我自己的API中发送到另一个API的值,但我不想只是在查询字符串中传递它们.

我可以在客户端中使用基本身份验证将用户名和密码添加到HttpRequestMessage身份验证标头中,然后在我的ASP.NET Core 2.0 API控制器操作中提取该标头吗?

我的客户端会在调用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));
Run Code Online (Sandbox Code Playgroud)

而且,我的API控制器动作会启动这样的事情;

    [HttpGet()]
    public IActionResult GetUploadedFileList([FromQuery]int pageNumber, [FromQuery]int pageSize)
    {

        //Extract Authentication header values for username and password

    }
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供如何从HTTPGet请求获取Authorization标头的示例

我意识到我可以使用HTTPPost [FromBody]轻松完成此操作,但我的用例要求此方法为HTTGet.

在此先感谢您的帮助.

编辑1 - 解决方案

由于此链接提供了一些提示,我能够让下面的代码工作.虽然这似乎很多工作,所以如果有人有更好或更清洁的解决方案,请发布你的例子.

    [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);

    }
Run Code Online (Sandbox Code Playgroud)

Tod*_*ier 17

ASP.NET Core支持[FromHeader]动作参数的属性,类似于[FromBody][FromQuery].因此,[FromHeader]string authorization在您的操作中添加一个arg将使您的解决方案脱离几行,并使该方法更易于测试,因为您可以避免访问该Request对象.