首页 文章

500在asp .net CORE / MVC 6应用程序中设置Swagger时出错

提问于
浏览
20

我正在尝试在新的asp .net CORE / MVC 6项目中设置一个基本的swagger API文档,并从swagger UI接收500错误: 500 : http://localhost:4405/swagger/v1/swagger.json

我的启动类中包含以下代码:

using Swashbuckle.SwaggerGen;
using Swashbuckle.SwaggerGen.XmlComments;
using Swashbuckle.Application;
....
public void ConfigureServices(IServiceCollection services)
{
  ...
  services.AddSwaggerGen();
  services.ConfigureSwaggerDocument(options =>
  {
    options.SingleApiVersion(new Info
    {
        Version = "v1",
        Title = "Blog Test Api",
        Description = "A test API for this blogpost"
    });
  });
}

然后在Configure下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
....
  app.UseSwaggerGen();
  app.UseSwaggerUi();
....
}

当我构建并运行项目时,当我转到swagger / UI / index.html时,UI会出现,但会显示上面的500错误 . 当我转到swagger / v1 / swagger.json链接时,控制台会给出以下500错误: Failed to load resource: the server responded with a status of 500 (Internal Server Error)

有什么方法可以找出500的根本原因或在swagger中启用任何额外的调试来弄清楚它为什么抛出这个错误?根据我所看到的一些教程,只有基础实现需要启动时才有 . 如果我能提供任何其他信息,请告诉我 .

编辑:这是针对rc1,可能与目前的新netcore 1.0无关(2016年6月29日)

12 回答

  • 0

    最初我也遇到了500错误 . 在堆栈跟踪的深处,它说:System.NotSupportedException:路径'api / hotels'的无界HTTP谓词 . 你错过了HttpMethodAttribute吗?

    事实证明我错过了一个api方法的HttpGet属性:

    [Microsoft.AspNetCore.Mvc.HttpGet]
    
  • 0

    如果有人想知道Swagger的堆栈跟踪中的确切错误,请请求URL:

    <your-app-url>/swagger/v1/swagger.json
    

    或者,单击浏览器开发工具控制台中的 swagger.json 链接:

    Chrome DevTools with error log

  • 54

    首先,您可以通过在Configure()上添加 app.UseDeveloperExceptionPage(); 来启用de developer exception页面,以便更好地了解哪个是根本原因 . 看看here

    在我的情况下,问题是我必须安装 Microsoft.AspNetCore.StaticFiles nuget才能使Swagger工作 .

    还尝试卸载/重新安装 Swashbuckle.AspNetCore nuget .

  • 0

    当我的一个函数被标记为 public 时,我收到此错误,但并不是一个可以直接调用的Web服务 .

    将功能更改为 private 使错误消失 .

    或者,在 public 函数之前,您可以放置 [NonAction] 命令,告诉Swagger忽略它 .

    [NonAction]
    public async Task<IActionResult> SomeEvent(string id)
    { 
       ...
    }
    

    (我希望Swagger实际报告导致这个问题的函数的名称,而不仅仅是抱怨它不再能找到“../swagger/v1/swagger.json”文件......这不是特别有用 . )

  • -1

    此外,如果我可以添加,当你在控制器的根级别路由时,swagger设置不喜欢它 . 例如:

    不要这样做:

    [Produces("application/json")]
    [Route("/v1/myController")]
    [Authorize]
    public class myController
    {
        [SwaggerResponse((int)System.Net.HttpStatusCode.OK, Type = typeof(RestOkResponse<Response>))]
        [SwaggerResponse((int)System.Net.HttpStatusCode.InternalServerError, Type = typeof(RestErrorResponse))]
        [SwaggerResponse((int)System.Net.HttpStatusCode.BadRequest, Type = typeof(RestErrorResponse))]
        [SwaggerResponse((int)System.Net.HttpStatusCode.Forbidden, Type = typeof(RestErrorResponse))]
        [SwaggerResponse((int)System.Net.HttpStatusCode.NotFound)]
        [HttpPost]
        [Authorize()]
        public async Task<IActionResult> Create([FromBody] MyObject myObject)
        {
            return Ok();
        }
    }
    

    做这个:

    [Produces("application/json")]
    [Authorize]
    public class myController
    {
        [SwaggerResponse((int)System.Net.HttpStatusCode.OK, Type = typeof(RestOkResponse<Response>))]
        [SwaggerResponse((int)System.Net.HttpStatusCode.InternalServerError, Type = typeof(RestErrorResponse))]
        [SwaggerResponse((int)System.Net.HttpStatusCode.BadRequest, Type = typeof(RestErrorResponse))]
        [SwaggerResponse((int)System.Net.HttpStatusCode.Forbidden, Type = typeof(RestErrorResponse))]
        [SwaggerResponse((int)System.Net.HttpStatusCode.NotFound)]
        [HttpPost("/v1/myController")]
        [Authorize()]
        public async Task<IActionResult> Create([FromBody] MyObject myObject)
        {
            return Ok();
        }
    }
    

    我花了一段时间才发现我收到内部服务器错误的原因是因为这个路由问题 . 希望这有助于某人!

  • 2

    当我添加参数版本时,它可以工作

    services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
            });
    
  • -2

    可能很明显,但除了缺少 HttpGetHttpPost 属性外,不要忘记区分post方法 .

    您可能有2种不同的方法(名称不同)标有 HttpPost ,这也会导致此类问题 . 请记住在属性中指定方法名称: [HttpPost("update")] .

  • 0

    要查看异常的来源

    • 打开chrome浏览器

    • 打开开发人员工具

    • 在控制台选项卡中查看例外

    • 修复它 .

  • 2

    也有这个问题 . 就我而言,它是由同一控制器中的两个 endpoints 引起的,具有相同的路由和方法名称(但参数类型不同) . 当然,很明显,这可能是糟糕的做法,所以我改变了 endpoints 名称,一切都很顺利 .

  • 3

    在某些情况下, router of controller 是重复的 . 查看最后修改的 controller .

  • 0

    看看这个项目 . https://github.com/domaindrivendev/Ahoy/tree/master/test/WebSites/Basic

    这个repo来自Swashbuckle的所有者,是一个基本的ASP.NET 5 Sample应用程序,这可以帮助你纠正配置你的中间件(并注意它们的命令,这很重要,例如,使用“app.UseSwaggerGen (); app.UseSwaggerUi();在app.UseMvc();)之后

    要在您的applcation中启用日志记录,请查看:https://docs.asp.net/en/latest/fundamentals/logging.html?highlight=logging(日志将在"wwwroot"文件夹中生成

  • 0

    Swagger的设置因版本而异 . 这个答案适用于Swashbuckle 6.0.0-beta9和Asp.Net Core 1.0 . 在Startup.cs的ConfigureServices方法内,您需要添加 -

    services.AddSwaggerGen(c =>
        {
          c.SingleApiVersion(new Info
          {
            Version = "v1",
            Title = "My Awesome Api",
            Description = "A sample API for prototyping.",
            TermsOfService = "Some terms ..."
          });
        });
    

    然后在Configure方法中,您必须添加 -

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
    
        app.UseMvc();
        app.UseSwaggerGen();
        app.UseSwaggerUi();
    }
    

    确保你在Startup.cs中引用 -

    使用Swashbuckle.SwaggerGen.Generator;

    我的project.json文件看起来像 -

    "dependencies": {
        "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
        "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
        "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
        "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.0-rc2-final",
        "Microsoft.EntityFrameworkCore.Tools": "1.0.0-*",
        "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
        "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
        "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
        "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
        "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
        "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",
        "Swashbuckle": "6.0.0-beta9"
      },
    
      "tools": {
        "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
          "version": "1.0.0-preview1-final",
          "imports": "portable-net45+win8+dnxcore50"
        },
        "Microsoft.EntityFrameworkCore.Tools": {
          "version": "1.0.0-preview1-final",
          "imports": [
            "portable-net45+win8+dnxcore50",
            "portable-net45+win8"
          ]
        }
      },
    
      "frameworks": {
        "net452": { }
      },
      "buildOptions": {
        "emitEntryPoint": true,
        "preserveCompilationContext": true,
        "xmlDoc": false
      },
    
      "publishOptions": {
        "include": [
          "wwwroot",
          "Views",
          "appsettings.json",
          "web.config"
        ]
      },
    
      "scripts": {
        "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
      }
    }
    

相关问题