Swashbuckle 5找不到我的ApiControllers

Bil*_*one 26 c# iis asp.net-web-api swashbuckle

我真的需要我的WebAPI 2项目的API文档,我使用了Swashbuckle 5 NuGet包.开箱即用,我可以点击{myrooturl}/swagger并弹出一个UI,但那里没有控制器,方法或任何东西.只是我的标题:[base url:/EM.Services,api version:v1]

我看了一下Swashbuckle文档,因为我正在使用由IIS托管的OWIN,所以我修改了SwaggerConfig:

c.RootUrl(req => req.RequestUri.GetLeftPart(UriPartial.Authority) + req.GetRequestContext().VirtualPathRoot.TrimEnd('/'));
Run Code Online (Sandbox Code Playgroud)

根据这个文档:https://github.com/domaindrivendev/Swashbuckle/blob/1326e753ce9b3a823b3c156b0b601134692ffc58/README.md#transitioning-to-swashbuckle-50

我还设置了项目的构建以生成XML文档,并将SwaggerConfig指向它:

    private static string GetXmlCommentsPath()
    {
        // tried with an without the \bin
        return String.Format(@"{0}\bin\EM.Services.XML", AppDomain.CurrentDomain.BaseDirectory);
    }
Run Code Online (Sandbox Code Playgroud)

我不确定XML文档的工作/不工作是否与它有关,因为我在swagger-ui页面上完全没有控制器.

值得一提的是,我的所有控制器都继承自BaseController,而BaseController又继承自ApiController.

我的WebApiConfig有什么东西搞砸了吗?

    public static void Register(HttpConfiguration config)
    {

        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        config.Filters.Add(new ValidateModelAttribute());

        config.Filters.Add(new BaseAuthenticationAttribute());

        config.MapHttpAttributeRoutes();

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

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
Run Code Online (Sandbox Code Playgroud)

我的具体控制器看起来都是这样的(我已经尝试为ApiController调试BaseController并且没有变化):

[RoutePrefix("api/whatever")]
public class FooController : BaseController
Run Code Online (Sandbox Code Playgroud)

并且我的Base控制器没有做太多(还),只有一个属性:

[BuildClaims]
public abstract class BaseController : ApiController
Run Code Online (Sandbox Code Playgroud)

空页面持续使用IIS Express或完整的IIS.

更新:我做的一个人为控制器的例子非常基本.它也没有出现,因为我仍然没有任何东西的锅炉板swagger ui.

/// <summary>
/// I am a test
/// </summary>
[RoutePrefix("api/dummy")]
public class DummyController : ApiController
{
    [HttpGet]
    [Route("foo")]
    public int Foo()
    {
        return 42;
    }
}
Run Code Online (Sandbox Code Playgroud)

Sum*_*ngi 23

我被卡住了......这些答案并没有完全帮助我......虽然他们把我带到了那里.只是为了节省其他人一些时间:

您必须从OWIN传递http配置,然后在其上注册而不是使用GlobalConfiguration类,如下所示:

//starup.cs
public void Configuration(IAppBuilder app)
    {
        Config = new HttpConfiguration();
        WebApiConfig.Register(Config);

        app
            .UseResponseLogging()
            .UseRequestLogging()
            .UseHttpErrors()
            .UseExceptionLogging()
            .UseWebApi(Config);

        HandlerConfig.Register(Config);

        SwaggerConfig.Register(Config);
    }
Run Code Online (Sandbox Code Playgroud)

并在swagger配置文件中,将register方法更改为:

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

        config
            .EnableSwagger(c =>
                {...
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 谢谢!这对我有用,但另外我还必须删除SwaggerConfig.cs文件最顶层的行([assembly:PreApplicationStartMethod ...).在我删除它之前,我收到"参数计数不匹配"错误 (6认同)

Bil*_*one 21

我发现了这个问题.在创建一个空的测试项目之后,我注意到WebApiConfiguration是从global.asax app start注册的,而不是OWIN启动类(就像我做的那样).

由于Swagger/Swashbuckle挂钩到GlobalConfiguration并且还认为OWIN启动和Global.asax存在于不同的上下文中(我认为),修复是将WebAPI内容连接到Global.asax注册并使用OWIN的app对象的WebAPI.

相关位:

   // global asax
    protected void Application_Start(object sender, EventArgs e)
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
       // ... more stuff
    }

   //startup.cs
   public void Configuration(IAppBuilder app)
    {
        // This must happen FIRST otherwise CORS will not work.
        app.UseCors(CorsOptions.AllowAll);

        HttpConfiguration config = new HttpConfiguration();

        ConfigureAuth(app);

        // webapi is registered in the global.asax
        app.UseWebApi(config);

    }
Run Code Online (Sandbox Code Playgroud)

如上所述重新布线后,我现在可以在swagger UI中看到控制器和操作.


chr*_*389 5

我发现我有同样的问题。我创建了一个扩展方法来帮助

using Swashbuckle.Application;
using System.Web.Http;

public static class SwaggerExtensions
{
    public static HttpConfiguration EnableSwagger(this HttpConfiguration httpConfiguration)
    {
        httpConfiguration
            .EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API"))
            .EnableSwaggerUi();
        return httpConfiguration;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的 Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        HttpConfiguration httpConfiguration = new HttpConfiguration();

        httpConfiguration
            .EnableSwagger()    // <==== EXTENSION METHOD <==== //
            .MapHttpAttributeRoutes();

        httpConfiguration.Routes.MapHttpRoute(
            "DefaultApi",
            "api/{controller}/{id}",
            new {id = RouteParameter.Optional});

        appBuilder
            .UseWebApi(httpConfiguration);
    }
}
Run Code Online (Sandbox Code Playgroud)