英文:
How to access response header values
问题
我正在使用 .Net Core 7 进行 Web API 项目的开发。
在响应头中获取到了一些数值,因此我想将这些值存储在一个变量中。
请查看下面的截图,我想要获取
x-rate-limit-remaining
的值。
英文:
I am working in web api project using .Net Core 7
I am getting values in Response headers.. So I want to access that values in one variable.
Please see below screenshot, I want to get value of
x-rate-limit-remaining
答案1
得分: 1
try
{
HttpClient client = new();
using var response = await client.GetAsync(URL);
var HeaderKey = "x-rate-limit-remaining";
if (response.Headers.Contains(HeaderKey))
{
var val = response.Headers.GetValues(HeaderKey).FirstOrDefault();
Console.WriteLine(val);
}
else
{
Console.WriteLine($"the key '{HeaderKey}' not found in the headers!");
}
}
catch (Exception ee)
{
Console.Error.WriteLine(ee.Message);
}
英文:
try
{
HttpClient client = new();
using var response = await client.GetAsync(URL);
var HeaderKey = "x-rate-limit-remaining";
if (response.Headers.Contains(HeaderKey))
{
var val = response.Headers.GetValues(HeaderKey).FirstOrDefault();
Console.WriteLine(val);
}
else
{
Console.WriteLine($"the key '{HeaderKey}' not found in the headers!");
}
}
catch (Exception ee)
{
Console.Error.WriteLine(ee.Message);
}
答案2
得分: 0
你可以使用 TryGetValues
与 StringValues
:
var headers = response.Headers;
string role = "";
if (headers.TryGetValues("Role", out Microsoft.Extensions.Primitives.StringValues headerValues))
{
role = headerValues.FirstOrDefault();
}
或者使用 IEnumerable<string>
:
var headers = response.Headers;
string role = "";
if (headers.TryGetValues("Role", out IEnumerable<string> headerValues))
{
role = headerValues.FirstOrDefault();
}
英文:
You can use TryGetValues with StringValues:
var headers = response.Headers;
string role = "";
if (headers.TryGetValues("Role", out Microsoft.Extensions.Primitives.StringValues headerValues))
{
role = headerValues.FirstOrDefault();
}
Or use IEnumerable<string>:
var headers = response.Headers;
string role = "";
if (headers.TryGetValues("Role", out IEnumerable<string> headerValues))
{
role = headerValues.FirstOrDefault();
}
答案3
得分: 0
根据你的以前的案例,
你可以尝试以下方法:
if (HttpContext.Response.Headers.ContainsKey("x-rate-limit-remaining"))
{
var header = HttpContext.Response.Headers["x-rate-limit-remaining"];
}
例如,在中间件中:
app.Use(async (context, next) =>
{
if (context.Response.Headers.ContainsKey("x-rate-limit-remaining"))
{
var header = context.Response.Headers["x-rate-limit-remaining"];
}
await next.Invoke();
});
英文:
Based on your former case
You could try as below:
if (HttpContext.Response.Headers.ContainsKey("x-rate-limit-remaining"))
{
var header = HttpContext.Response.Headers["x-rate-limit-remaining"];
}
For example in middleware :
app.Use(async (context, next) =>
{
if (context.Response.Headers.ContainsKey("x-rate-limit-remaining"))
{
var header = context.Response.Headers["x-rate-limit-remaining"];
}
await next.Invoke();
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论