我有两个webapi(.net core(应用程序,例如WebAPI1和WebAPI2。现在,我正在呼叫/消费WebAPI2的WebAPI1(端点(。如何从WebAPI2应用程序中获取WebAPI1 HTTP标头值?
尝试使用request.header;但没有获得WebAPI1标题。这是控制器操作中编写的代码 -
(Request?.Headers ?? throw new Exception("Http Header is Null")).ToDictionary<KeyValuePair<string, StringValues>, string, string>(
header => header.Key, header => header.Value);
在这里,我正在获取WebAPI2标题。
用于从API2调用Web API1,您可以尝试HttpClient
喜欢:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly HttpClient _client;
public ValuesController(IHttpClientFactory httpClientFactory)
{
_client = httpClientFactory.CreateClient();
}
// GET api/values
[HttpGet]
public async Task<ActionResult<IEnumerable<string>>> Get()
{
var response = await _client.GetAsync("https://localhost:44349/api/values");
var headers = response.Headers.ToList();
return new string[] { "value1", "value2" };
}
并通过
注册HttpClient
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
我错过了我的应用程序中的"启用cors"。
https://learn.microsoft.com/en-us/aspnet/core/core/security/cors?view = aspnetcore-2.2
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com")
**.AllowAnyHeader()**
.AllowAnyMethod();
});
在此处通过自定义标头需要"允许的人"。现在我能够捕获自定义的HTTP标头。