Swagger 在 OWIN Startup Web API C# 中不起作用

Posted

技术标签:

【中文标题】Swagger 在 OWIN Startup Web API C# 中不起作用【英文标题】:Swagger isn't working in OWIN Startup Web API C# 【发布时间】:2020-12-09 14:17:00 【问题描述】:

我在我的 Web API 的 OWIN startup.cs 文件中实现了 Swagger,但是当我尝试打开 Swagger UI 页面时,它显示 HTTP Error 404.0 - Not Found

检查 Swagger UI 的 URL:https://localhost:5001/swagger

这是我的实现,请帮我解决我所缺少的。

Startup.cs

public class Startup

   public void Configuration(IAppBuilder app)
   
     app.Map("/api", map =>  ConfigureApiArea(map); );
   

   private void ConfigureApiArea(IAppBuilder map)
   
            var config = CreateTypedConfiguration<BaseApiController>();

            //Json Settings
            JsonFormatterSettings(config);

            ConfigureAutofac(config, map);
            ConfigureOAuth(map);

            config.EnableCors(new EnableCorsAttribute("*", "*", "*", "Paging-Headers,X-Error"));
            map.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            config.EnsureInitialized();


            map.UseWebApi(config);
   

   private HttpConfiguration CreateTypedConfiguration<TBaseController>() where TBaseController : IHttpController
   
            var config = new HttpConfiguration();
            config.Services.Replace(typeof(IHttpControllerTypeResolver), new 
            TypedHttpControllerTypeResolver<TBaseController>());
            config.EnableSwagger();
            config.MapHttpAttributeRoutes(new TypedDirectRouteProvider<TBaseController>());
            return config;
   


SwaggerExtensions.cs

 public static class SwaggerExtensions
    
        public static HttpConfiguration EnableSwagger(this HttpConfiguration httpConfiguration)
        
            httpConfiguration
                .EnableSwagger(c => c.SingleApiVersion("v1", "MyWebAPI"))
                .EnableSwaggerUi();

            return httpConfiguration;
        
    

MyController.cs

public class MyController : BaseApiController

    [AllowAnonymous]
    [HttpGet]
    [Route("orders/orderId")]
    public IHttpActionResult GetOrder([FromUri]string orderId) 
        return Ok();
    

BaseApiController.cs

 public class BaseApiController : ApiController  

【问题讨论】:

你试过https://localhost:5001/api/swagger吗? 是的,我做了 localhost:5001/api/swagger 和 localhost:5001/api/swagger/ui,但还是没有相同的 404 【参考方案1】:

事实上https://localhost:5001/api/swagger正如@Dai所建议的那样,它不起作用的原因是因为方法ConfigureAutofac(config, map)中的自定义MessageHandlers(OP在代码中没有显示)没有处理请求包含/swagger 的路径。

方法ConfigureAutofac(config, map)内的MessageHandler代码省略:

private void ConfigureAutofac(HttpConfiguration config, IAppBuilder app)

    var builder = new ContainerBuilder();    
    
    //code omitted for brevity ...

    //Register Web API controllers.
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly())
    .InstancePerRequest();

    //Register the Autofac filter provider.
    builder.RegisterWebApiFilterProvider(config);

    //Register the Autofac model binder provider.
    builder.RegisterWebApiModelBinderProvider();

    //code omitted for brevity ...
    
    var container = builder.Build();

    //Set the dependency resolver to be Autofac.
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    config.MessageHandlers.Insert(0, new ApiDelegatingHandler());
    config.MessageHandlers.Insert(1, new ActivityLogHandler());

    app.UseAutofacMiddleware(container);
    app.UseAutofacWebApi(config);

自定义MessageHandler 中唯一需要的更改是处理此问题,如下所示:

public class ApiDelegatingHandler : DelegatingHandler

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    
        if (request.RequestUri.PathAndQuery.Contains("/swagger")) 
            return await base.SendAsync(request, cancellationToken);

        //code omitted for brevity ...
    

【讨论】:

以上是关于Swagger 在 OWIN Startup Web API C# 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

OWIN Startup 类与 WebAPIConfig.Register 方法一起执行

1.6 OWIN集成

Owin 学习系列1. 第一个 Owin 程序

OWIN显示死亡的黄色屏幕

OWIN 承载令牌认证

Owin管道与asp.net管道模型