【问题标题】:WebApi and using SwaggerWebApi 和使用 Swagger
【发布时间】:2018-05-16 23:42:05
【问题描述】:

我已经实现了一个具有 swashbuckle/swagger 和自定义 DelegatingHandler 的 WebApi 项目。 我添加了一个 SwaggerAccessMessageHandler 来检查是否发出了招摇请求,在这种情况下我不希望我的自定义处理程序运行。

我已将消息处理程序注册为

GlobalConfiguration.Configuration.MessageHandlers.Add(new SwaggerAccessMessageHandler());

自定义实现:

public class SwaggerAccessMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (IsSwagger(request))
        {
            var response = request.CreateResponse(HttpStatusCode.Unauthorized);
            return Task.FromResult(response);
        }
        else
        {
            return base.SendAsync(request, cancellationToken);
        }
    }

    private bool IsSwagger(HttpRequestMessage request)
    {
        return request.RequestUri.PathAndQuery.StartsWith("/swagger");
    }
}

但是当我可以使用 /swagger 我的 WebApi 时,我得到一个空白页面而不是 swagger ui。

更新:好的,我现在已经删除了 Swagger 处理程序。 我添加了一个新的 AuthenticationHandler 来检查传入请求查询字符串中的有效用户密钥。我现在无法访问 swagger。 有没有办法解决这个问题,所以当我想访问 swagger 时,我的自定义处理程序不会被调用?

【问题讨论】:

  • 请参阅上面的更新。

标签: c# swagger


【解决方案1】:

您有一个空白页面,因为您正在使用 REST 服务并且您没有在正文中说任何内容。您的浏览器将返回一个对用户不可见的标头 401。 您必须更改对以下内容的响应

var response = request.CreateResponse(HttpStatusCode.Unauthorized,"You are not authorized");

更新 UPDATE: Ok I have removed the Swagger handler for now. I have added a new AuthenticationHandler which checks for a valid userKey in the incoming request querystring. I cannot access swagger now. Is there a way around this so when I want to access swagger my custom handler is not called? 没有 DelegatingHanler 被作为入口点执行。 跟随 webapi Pipeline 的工作原理:

您可能会注意到,您无法控制绕过任何消息处理程序的管道。 在您的 AuthenticationHandler 中,您必须检查您的 PathAndQuery 是否包含 swagger 只需执行以下操作

base.SendAsync(request, cancellationToken);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2021-08-03
    相关资源
    最近更新 更多