简体   繁体   English

Swashbuckle文档在加载时出现NullReferenceException

[英]Swashbuckle documentation NullReferenceException on load

We're currently encountering a problem when trying to access our documentation. 我们在尝试访问我们的文档时遇到了问题。 We currently host a WebAPI2 project in a Webforms web application which has worked well for us for nearly a year now. 我们目前在Webforms Web应用程序中托管了一个WebAPI2项目,该项目近一年来一直运行良好。 We are using Swashbuckle 5.2.2 but I did update to the current version to see if it would address the issue. 我们正在使用Swashbuckle 5.2.2,但我确实更新了当前版本,看它是否能解决这个问题。 It didn't happen to magically fix the issue so it is now reverted back to 5.2.2 since we're about to make a release. 它并没有巧妙地修复这个问题所以它现在又恢复到5.2.2,因为我们即将发布。

A number of weeks ago all of a sudden the documentation started throwing exceptions when attempting to open it. 几个星期前,文档突然在尝试打开它时开始抛出异常。 The only information we've been able to gather so far is the following which is output to the browser: 到目前为止我们能够收集的唯一信息是以下输出到浏览器的信息:

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Object reference not set to an instance of an object.</ExceptionMessage>
<ExceptionType>System.NullReferenceException</ExceptionType>
<StackTrace>   at ᜄ.ᜀ.<>c.ᜀ(Task`1 A_0)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Cors.CorsMessageHandler.<SendAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()
</StackTrace>
</Error>

We have identified the build at which it stopped working and have inspected the code commit that triggered the build. 我们已经确定了它停止工作的构建,并检查了触发构建的代码提交。 However, there were no commits to the WebAPI project at all, nor anything other than some CSS in the main webapp which wouldn't affect the Swagger documentation. 但是,WebAPI项目根本没有提交,除了主Web应用程序中的某些CSS之外没有其他任何提交,这些CSS不会影响Swagger文档。

We have compared the web application folders between the two builds and the only differences other than the minor CSS differences are the project assemblies that got recompiled. 我们比较了两个构建之间的Web应用程序文件夹,除了较小的CSS差异之外,唯一的区别是重新编译的项目程序集。 Each build is built fresh from source control. 每个构建都是从源代码控制中新建的。

I've inspected the WebAPI2 project assembly and the custom swagger resource files (an image, html, and css file) are embedded correctly in both builds. 我检查了WebAPI2项目程序集,并在两个版本中正确嵌入了自定义swagger资源文件(图像,html和css文件)。

Here is our SwaggerConfig content (a few identifying names changed): 这是我们的SwaggerConfig内容(一些识别名称已更改):

const string webApiXmlDocFileName = "WebAPI2.xml";
const string modelXmlDocFileName = "Core.xml";

GlobalConfiguration.Configuration
    .EnableSwagger("api/docs/{apiVersion}", c =>
    {
        c.IgnoreObsoleteActions();
        c.IgnoreObsoleteProperties();
        c.DescribeAllEnumsAsStrings();
        c.IncludeXmlComments(webApiXmlDocFileName);
        c.IncludeXmlComments(modelXmlDocFileName);
        c.DocumentFilter<AlphabeticSortOperationFilter>();

        c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
        c.SingleApiVersion("v1", "API Reference");

        c.Schemes(new[] { "http", "https" });
        c.OAuth2("oauth2")
            .Description("OAuth2 Implicit Grant")
            .TokenUrl("/api/oauth2/token")
            .Flow("password")
            .Scopes(scopes =>
            {
                scopes.Add("clientid", "try out simple api");
            });
        c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();
    })
    .EnableSwaggerUi("api/docs/ui/{*assetPath}", c =>
    {
        // Specify our custom templates isntead of defaults
        c.InjectStylesheet(Assembly.GetExecutingAssembly(), "WebAPI2.SwashbuckleExtensions.index.css");
        c.CustomAsset("index", Assembly.GetExecutingAssembly(), "WebAPI2.SwashbuckleExtensions.index.html");
        c.CustomAsset("logo", Assembly.GetExecutingAssembly(), "WebAPI2.SwashbuckleExtensions.Logo-white.png");
        c.EnableOAuth2Support("clientid", "realm", "project");
        c.DisableValidator();
    });

We aren't getting anything in the logs and walking through all of our code doesn't expose the error on our end. 我们没有在日志中获得任何内容,并且遍历我们的所有代码都不会在我们的结尾处暴露错误。

Does anyone have any suggestions on how to further dig into this? 有没有人对如何进一步深入研究? We're kind of at a loss here since we can't capture where the error is coming from in the request routing. 我们在这里有点茫然,因为我们无法捕获请求路由中的错误来源。 Any help would be appreciated. 任何帮助,将不胜感激。

EDIT I finally tracked down a little more info that might shed some light on this issue. 编辑我终于找到了一些可能会对这个问题有所了解的信息。

We use a 3rd party control in our application that it looks like hosts its own WebAPI instance in order to handle its own RESTful calls. 我们在我们的应用程序中使用第三方控件,它看起来像主机自己的WebAPI实例,以便处理自己的RESTful调用。 The error described above occurs when a specific method of theirs is called during initialization of the webapp. 当在webapp初始化期间调用他们的特定方法时,会发生上述错误。 I have contacted them to see if this call is required or what the ramifications of not making it might be. 我已经联系过他们,看看是否需要这个电话会议,或者说是不是这样做的后果。

The question becomes, is there a way to have Swashbuckle ignore an assembly or class entirely? 问题是,有没有办法让Swashbuckle完全忽略一个程序集或类? Since it's 3rd party we can't modify it to add custom attributes and using filters won't work as the exception is already thrown at that point. 由于它是第三方,我们无法修改它以添加自定义属性,并且使用过滤器将无法正常工作,因为此时已经抛出了异常。

Not sure if this is the situation you had, but I had same System.NullReferenceException: 'Object reference not set to an instance of an object.' 不确定这是否是你的情况,但我有相同的System.NullReferenceException:'对象引用未设置为对象的实例。 exception in line which had 有例外的

foreach (var group in apiExplorer.ApiDescriptions ): foreach( apiExplorer.ApiDescriptions中的 var组):

c.MultipleApiVersions(
                                (apiDescription, version) => apiDescription.GetGroupName() == version,
                                info =>
                                {
                                foreach (var group in apiExplorer.ApiDescriptions)
                                    {
                                        var description = ....

By eliminating line by line which I added I concluded I made a mistake in [Route] attribute in API Controller action. 通过逐行删除我添加的结论,我在API Controller操作中的[Route]属性中犯了一个错误。 I didn't close the route with '/' 我没有用'/'关闭路线

So, this didn't work 所以,这不起作用

[Route("templateFields/{templateFieldId:int}/inputtype")]

But this worked 但这很有效

[Route("templateFields/{templateFieldId:int}/inputtype/")] - not the / at the end . [Route(“templateFields / {templateFieldId:int} / inputtype /”)] - 而不是/的结尾

That caused the exception! 那引起了异常!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM