Swagger isn't working in OWIN Startup Web API C#

无人久伴 提交于 2021-02-11 12:53:28

问题


I've implemented Swagger in the OWIN startup.cs file in my Web API, but when I try to open Swagger UI page it says HTTP Error 404.0 - Not Found

URL to check Swagger UI: https://localhost:5001/swagger

Here is my implementation, please help me what I'm missing.

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 { }

回答1:


It was in fact https://localhost:5001/api/swagger as @Dai suggested, the reason it was not working was because of the custom MessageHandlers inside the method ConfigureAutofac(config, map) (not shown in the code by OP) were not handling the requests with path with /swagger in them.

MessageHandler code inside the method ConfigureAutofac(config, map) omitted:

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

The only change required in the custom MessageHandler was to handle this, as below:

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 ...
    }
}


来源:https://stackoverflow.com/questions/63501767/swagger-isnt-working-in-owin-startup-web-api-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!