【问题标题】:How to read a custom header in Swashbuckle? [duplicate]如何在 Swashbuckle 中读取自定义标题? [复制]
【发布时间】:2018-03-22 15:14:03
【问题描述】:

我使用以下代码向操作添加自定义标头:

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

但现在我需要读取该值。我试过这段代码,但自定义标头不存在:

 System.Web.HttpContext.Current.Items.contains("requestId")

【问题讨论】:

  • 参数的名称是RequestId,但是你正在寻找参数requestId。您确定这不是区分大小写的问题吗?
  • 试试 HttpContext.Current.Request.Headers["requestid"]

标签: asp.net-mvc swagger swashbuckle


【解决方案1】:

试试这个:

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();
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2018-04-21
    • 2020-08-19
    • 2022-12-03
    • 1970-01-01
    • 2019-10-03
    相关资源
    最近更新 更多