Swashbuckle 5找不到我ApiControllers [英] Swashbuckle 5 can't find my ApiControllers

查看:999
本文介绍了Swashbuckle 5找不到我ApiControllers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个地步,我真的需要API文档,我的WebAPI 2项目,我用了5 Swashbuckle包的NuGet。开箱即用,我可以打{} myrooturl /招摇和UI弹出,但没有控制器,方法,或任何东西在那里。只是我的标题:[基础网址:/EM.Services,API版本:V1]

我接过一看Swashbuckle文档,而且由于我使用的是IIS托管OWIN,我修改了SwaggerConfig有:

  c.RootUrl(REQ =方式> req.RequestUri.GetLeftPart(UriPartial.Authority)+ req.GetRequestContext()VirtualPathRoot.TrimEnd('/'));

根据这个文档:<一href=\"https://github.com/domaindrivendev/Swashbuckle/blob/1326e753ce9b3a823b3c156b0b601134692ffc58/README.md#transitioning-to-swashbuckle-50\" rel=\"nofollow\">https://github.com/domaindrivendev/Swashbuckle/blob/1326e753ce9b3a823b3c156b0b601134692ffc58/README.md#transitioning-to-swashbuckle-50

我还设置了项目的构建生成XML文档,并指出我的SwaggerConfig把它与

 私有静态字符串GetXmlCommentsPath()
    {
        //试图用一个没有\\ BIN
        返回的String.Format(@{0} \\ BIN \\ EM.Services.XML,AppDomain.CurrentDomain.BaseDirectory);
    }

我不知道如果XML文档的工作/不工作有什么关系呢,虽然,我得到了招摇的UI页面上绝对没有任何的控制器。

有关它的价值,我所有的控制器继承从BaseController,这反过来从ApiController继承。

是不是有什么扭曲我的WebApiConfig?

 公共静态无效的注册(HttpConfiguration配置)
    {        CONFIG.SUP pressDefaultHostAuthentication();
        config.Filters.Add(新HostAuthenticationFilter(OAuthDefaults.AuthenticationType));        config.Filters.Add(新ValidateModelAttribute());        config.Filters.Add(新BaseAuthenticationAttribute());        config.MapHttpAttributeRoutes();        config.Routes.MapHttpRoute(
            名称:DefaultApi
            routeTemplate:API / {控制器} / {行动} / {ID}
            默认:新{ID = RouteParameter.Optional}
        );        VAR jsonFormatter = config.Formatters.OfType&LT; JsonMediaTypeFormatter&GT;()(第)。
        jsonFormatter.SerializerSettings.ContractResolver =新CamelCasePropertyNamesContractResolver();
        jsonFormatter.SupportedMediaTypes.Add(新MediaTypeHeaderValue(text / html的));
    }

我的具体控制器的所有看起来像这样(我试过了胶层为BaseController和ApiController没有变化):

  [路线preFIX(API /无所谓)]
公共类FooController的:BaseController

和我的基本控制器没有做太多(还),只是有一个属性:

  [BuildClaims]
公共抽象类BaseController:ApiController

空页面仍然存在跨使用IIS防爆preSS或完全成熟的IIS。

更新:
一个人为的控制,我做了的例子是非常基本的。它也显示不出来,因为我仍然有什么也没有锅炉板招摇UI。

  ///&LT;总结&gt;
///我是一个测试
///&LT; /总结&gt;
[途径preFIX(API /哑)]
公共类DummyController:ApiController
{
    [HTTPGET]
    [路线(富)]
    公众诠释美孚()
    {
        返回42;
    }
}


解决方案

我发现这个问题。创建一个空的测试项目后,我注意到WebApiConfiguration正在从在Global.asax应用程序的开始,而不是OWIN启动类注册(像我一样)。

由于扬鞭/ Swashbuckle被钩住GlobalConfiguration,也考虑到OWIN启动和生活的Global.asax在不同环境下(我认为),修复是要连接你的WebAPI的东西从Global.asax中注册并拥有OWIN的应用对象使用的WebAPI。

相关位:

  //全球ASAX
    保护无效的Application_Start(对象发件人,EventArgs的发送)
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
       // ...更多的东西
    }   //startup.cs
   公共无效配置(IAppBuilder应用程序)
    {
        //这一定会发生,否则第一CORS将无法正常工作。
        app.UseCors(CorsOptions.AllowAll);        HttpConfiguration配置=新HttpConfiguration();        ConfigureAuth(应用);        //的WebAPI被登记在global.asax中
        app.UseWebApi(配置);    }

如上重装之后,我现在看到控制器和放大器;行动招摇UI。

I'm at a point where I really need API documentation for my WebAPI 2 project, and I used the Swashbuckle 5 NuGet package. Out of the box, I can hit {myrooturl}/swagger and a UI pops up, but there are no controllers, methods, or anything in there. Just my title: [ base url: /EM.Services , api version: v1 ]

I took a look at the Swashbuckle docs, and since I'm using OWIN which is hosted by IIS, I modified the SwaggerConfig with:

c.RootUrl(req => req.RequestUri.GetLeftPart(UriPartial.Authority) + req.GetRequestContext().VirtualPathRoot.TrimEnd('/'));

as per this doc: https://github.com/domaindrivendev/Swashbuckle/blob/1326e753ce9b3a823b3c156b0b601134692ffc58/README.md#transitioning-to-swashbuckle-50

I also setup the build of the project to generate the XML docs and pointed my SwaggerConfig to it with:

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

I'm not sure if the XML docs working/not-working has anything to do with it though, as I get absolutely no controllers on the swagger-ui page.

For what it's worth, all of my controller inherit from a BaseController, which in turn inherits from ApiController.

Is there something screwy with my 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"));
    }

My concrete controllers all look like this (I've tried subbing out BaseController for ApiController and there is no change):

[RoutePrefix("api/whatever")]
public class FooController : BaseController

and my Base controller doesn't do much (yet), just has an attribute:

[BuildClaims]
public abstract class BaseController : ApiController

The empty page persists across using IIS Express or full blown IIS.

Update: Example of a contrived controller I made that is really basic. It also does not show up, as I still have the boiler plate swagger ui with nothing in it.

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

解决方案

I found the problem. After creating an empty test project, I noticed that the WebApiConfiguration was being registered from the global.asax app start and not the OWIN startup class (like I did).

Since Swagger/Swashbuckle is hooking into the GlobalConfiguration and also given that OWIN startup and Global.asax live in different contexts (I think), the fix is to wire up your WebAPI stuff to register from Global.asax and to have OWIN's app object use WebAPI.

Relevant bits:

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

    }

After rewiring as above, I can now see controllers & actions in swagger UI.

这篇关于Swashbuckle 5找不到我ApiControllers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆