如何在 Swashbuckle 中读取自定义 header?
How to read a custom header in Swashbuckle?
我使用以下代码将自定义 header 添加到操作中:
public class RequestIdParameter : IOperationFilter
{
public void Apply(Swashbuckle.Swagger.Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation == null) return;
if (operation.parameters == null)
{
operation.parameters = new List<Parameter>();
}
var requestParameter = new Parameter
{
description = "RequestId",
@in = "header",
name = "RequestId",
required = true,
type = "string"
};
operation.parameters.Add(requestParameter);
}
}
但现在我需要读取该值。我试过这段代码,但自定义 header 不存在:
System.Web.HttpContext.Current.Items.contains("requestId")
试试这个:
if (HttpContext.Current.Request.Headers.Contains("RequestId"))
{
string value = HttpContext.Current.Request.Headers.GetValues("RequestId").FirstOrDefault();
}
或
IEnumerable<string> headerValues;
if (HttpContext.Current.Request.Headers.TryGetValues("RequestId", out headerValues))
{
string value = headerValues.FirstOrDefault();
}
我使用以下代码将自定义 header 添加到操作中:
public class RequestIdParameter : IOperationFilter
{
public void Apply(Swashbuckle.Swagger.Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation == null) return;
if (operation.parameters == null)
{
operation.parameters = new List<Parameter>();
}
var requestParameter = new Parameter
{
description = "RequestId",
@in = "header",
name = "RequestId",
required = true,
type = "string"
};
operation.parameters.Add(requestParameter);
}
}
但现在我需要读取该值。我试过这段代码,但自定义 header 不存在:
System.Web.HttpContext.Current.Items.contains("requestId")
试试这个:
if (HttpContext.Current.Request.Headers.Contains("RequestId"))
{
string value = HttpContext.Current.Request.Headers.GetValues("RequestId").FirstOrDefault();
}
或
IEnumerable<string> headerValues;
if (HttpContext.Current.Request.Headers.TryGetValues("RequestId", out headerValues))
{
string value = headerValues.FirstOrDefault();
}