无法在 WEB API .net 框架项目中设置 swagger UI

unable to setup swagger UI in WEB API .net framework project

我有这样的 SwaggerConfig 设置

public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;

        GlobalConfiguration.Configuration 
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "My.API");
                })
            .EnableSwaggerUi(c =>
                {                        
                });
    }
}

和这样的 WebApiConfig 设置

    public static class WebApiConfig
{
    /// <summary>
    /// Register Method for Configuration Settings.
    /// </summary>
    /// <returns>Returns a HttpConfiguration which is a complex object which represents a configuration of HttpServer.
    /// </returns>
    public static HttpConfiguration Register()
    {
        var config = new HttpConfiguration();

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.MessageHandlers.Add(new CancelledTaskBugWorkaroundMessageHandler());

        // SetupOData(config);

        // require authentication for all controllers
        config.Filters.Add(new AuthorizeAttribute());
        config.Filters.Add(new HostAuthenticationAttribute("Bearer"));

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "GetPagedData",
            routeTemplate: "{controller}/{pageNumber}/{pageSize}"
        );

        // Web API configuration and services
        config.EnableCors();

        // pulling out the XML for now -teg
        config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
            Newtonsoft.Json.ReferenceLoopHandling.Ignore;

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
            new MediaTypeHeaderValue("application/json-patch+json"));
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
            new MediaTypeHeaderValue("text/html"));

        var logger = new LoggerConfiguration()
            .ReadFrom.AppSettings()
            .CreateLogger();

        config.Services.Add(typeof(IExceptionLogger), new MedefisExceptionLogger(logger));
        config.Filters.Add(new CommonExceptionFilterAttribute());

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
        json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        config.Services.Replace(typeof(IDocumentationProvider),
             new XmlCommentDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/Medefis.API.XML")));
        return config;
    }
}

在 Startup.cs 中我调用 SwaggerConfig.Register() 几行之后我也调用 WebApiConfig.Register()

 public class Startup
{
    /// <summary>
    /// Configuration for IAppBuilder on MedefisAPIUri
    /// </summary>
    /// <param name="app"></param>
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        SwaggerConfig.Register();
        var logger = new LoggerConfiguration()
            .ReadFrom.AppSettings()
            .CreateLogger();

        logger.Information("Api Startup");

        AutoMapperConfiguration.Configure();
        //CreateFoldersOnFileSystem();

        app.UseCors(CorsOptions.AllowAll);
        JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
        AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityServer3.Core.Constants.ClaimTypes.Subject;

        if (ConfigurationManager.AppSettings["UseIdentityServer"] == "True")
        {
            app.UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = MedefisConstants.MedefisSTSConfig,
                    RequiredScopes = new[] { MedefisConstants.Scopes.api },
                    ClientId = MedefisConstants.Scopes.api,
                    ClientSecret = MedefisConstants.Secrets.InternalAPIClientSecret
                }
            );
        }

        // 
        builder.Register(c => new HttpContextWrapper(HttpContext.Current)).As<HttpContextBase>().InstancePerRequest();
        builder.RegisterType<ContactEmailRepository>().As<IContactEmailRepository>().InstancePerRequest();
        builder.RegisterType<EmailMedefisUsersHelper>().As<IEmailMedefisUsersHelper>().InstancePerRequest();
        builder.RegisterType<AgencyBiddingProfileService>().As<IAgencyBiddingProfileService>().InstancePerRequest();


        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        builder.RegisterType<UploadDocumentHelper>().As<IUploadDocumentHelper>().InstancePerRequest();

        builder.RegisterModule(new ValidationModule());

        //Service
        //builder.RegisterType<..... // su registerations goes here

        //Setup
        var config = WebApiConfig.Register();
        builder.RegisterWebApiFilterProvider(config);
        builder.RegisterInstance(config).As<HttpConfiguration>().SingleInstance().PropertiesAutowired();

        var container = builder.Build();
        config.EnableDependencyInjection();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        app.Use(typeof(WebApiAuthUserMiddleware));
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies"
        });

        config.EnsureInitialized();
    }
}

问题是,当我调用 http://localhost:xxxx/swagger 时,它重定向到 /swagger/ui/index 但我收到错误消息

No type was found that matches the controller named 'swagger'

请不要使用我正在使用的 Swashbuckle.Net45 版本 5.2.1

更新 在 routeTemplate 中使用“api/”作为路径前缀后:“api/{controller}/{id}”“

我能够加载 UI 但 none 的路径和定义是空的。

解决方案是不单独使用 SwaggerConfig.Register() 而是在 WebApiConfig 中进行此配置。