Google Code Prettify

ASP.NET Core 中使用 HttpClient 如何以動態的方式設定 Authorization標頭?

在 ASP.NET Core 中使用 HttpClient 來以動態方式設定 Authorization標頭,可以通過多種方法來實現。以下是一些常見的方法來設置 Authorization 標頭,其中包括基本身份驗證和使用 Bearer token。

使用 HttpClient 和 HttpClientFactory
HttpClientFactory 是 ASP.NET Core 中推薦的用來創建 HttpClient 的方式。它提供了更好的資源管理和性能。


1. 配置 HttpClientFactory
首先,在 Startup.cs 中配置 HttpClientFactory。

csharp


public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();

    services.AddControllersWithViews();
}



2. 使用 DI 獲取 HttpClient
在控制器或服務中通過依賴注入(Dependency Injection)獲取 HttpClient 並設置 Authorization 標頭。

csharp


using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

public class MyController : Controller
{
    private readonly IHttpClientFactory _httpClientFactory;

    public MyController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task GetDataAsync()
    {
        var client = _httpClientFactory.CreateClient();

        // 動態設置 Authorization 標頭
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_jwt_token_here");

        var response = await client.GetAsync("https://api.example.com/data");

        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsStringAsync();
            return Ok(data);
        }
        else
        {
            return StatusCode((int)response.StatusCode, response.ReasonPhrase);
        }
    }
}



使用 HttpRequestMessage
有時候,你可能需要對特定請求設置 Authorization 標頭。這可以使用 HttpRequestMessage 來實現。

csharp


public async Task GetDataAsync()
{
    var client = _httpClientFactory.CreateClient();

    var request = new HttpRequestMessage(HttpMethod.Get, "https://api.example.com/data");
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "your_jwt_token_here");

    var response = await client.SendAsync(request);

    if (response.IsSuccessStatusCode)
    {
        var data = await response.Content.ReadAsStringAsync();
        return Ok(data);
    }
    else
    {
        return StatusCode((int)response.StatusCode, response.ReasonPhrase);
    }
}



使用 DelegatingHandler
如果你需要在多個請求中動態設置 Authorization 標頭,可以使用 DelegatingHandler 來集中處理這個邏輯。


1. 創建 DelegatingHandler
創建一個自定義的 DelegatingHandler 來設置 Authorization 標頭。

csharp


public class AuthorizationHandler : DelegatingHandler
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public AuthorizationHandler(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var token = _httpContextAccessor.HttpContext.Session.GetString("jwt_token");
        
        if (!string.IsNullOrEmpty(token))
        {
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        }

        return await base.SendAsync(request, cancellationToken);
    }
}



2. 配置 HttpClient 以使用 DelegatingHandler
在 Startup.cs 中配置 HttpClient 使用這個 DelegatingHandler。

csharp


public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient("MyClient")
        .AddHttpMessageHandler();

    services.AddHttpContextAccessor();
    services.AddTransient();

    services.AddControllersWithViews();
}



3. 使用已配置的 HttpClient
在控制器或服務中使用已配置的 HttpClient。

csharp


public class MyController : Controller
{
    private readonly IHttpClientFactory _httpClientFactory;

    public MyController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task GetDataAsync()
    {
        var client = _httpClientFactory.CreateClient("MyClient");

        var response = await client.GetAsync("https://api.example.com/data");

        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsStringAsync();
            return Ok(data);
        }
        else
        {
            return StatusCode((int)response.StatusCode, response.ReasonPhrase);
        }
    }
}



總結
這些方法展示了如何在 ASP.NET Core 中使用 HttpClient 動態設置 Authorization 標頭。根據具體需求,可以選擇在每個請求中設置標頭、使用 DelegatingHandler 或是直接在 HttpRequestMessage 中設置標頭。這樣可以確保你的應用程序在進行 API 請求時安全且靈活。