Swagger在OWIN启动Web

Swagger在OWIN启动Web

本文介绍了Swagger在OWIN启动Web API C#中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Web API的OWIN startup.cs文件中实现了Swagger,但是当我尝试打开Swagger UI页面时,它说 HTTP错误404.0-未找到

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

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

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

推荐答案

实际上是@Dai所建议的 https://localhost:5001/api/swagger ,原因是它不起作用是由于方法 ConfigureAutofac(config,map)中的自定义 MessageHandlers (OP代码未显示)未处理路径为/的请求摇摇欲坠.

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 代码省略:

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 中唯一需要做的更改就是处理此问题,如下所示:

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

这篇关于Swagger在OWIN启动Web API C#中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:55