.NET Core

※This article is based on .NET Core2.2

配置 [edit]

默认的Swagger配置没有用户验证功能,需要配置一下,Swagger才能直接来测试API。

打开Program.cs,把builder.Services.AddSwaggerGen();这一句修改为:

builder.Services.AddSwaggerGen(c =>
{
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Description = "Bearer Token",
        Name = "Authorization",
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
        {
            new OpenApiSecurityScheme()
            {
                Reference=new OpenApiReference()
                {
                    Type=ReferenceType.SecurityScheme,
                    Id="Bearer"
                }
            },new string[]{ }
        }
    });
});

右上角会出现“Authorize”按钮

※注意:填写的字符串的前面需要加上“Bearer ”

Troubleshooting [edit]

Failed to load API definition [edit]

报出下面的错误

Failed to load API definition

为了查看具体的错误信息

https://localhost:端口号/swagger/v1/swagger.json
An unhandled exception occurred while processing the request.
SwaggerGeneratorException: Ambiguous HTTP method for action - SINOData.Controllers.OrderController.Success (SINOData). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable<ApiDescription> apiDescriptions, SchemaRepository schemaRepository)

Stack Query Cookies Headers Routing
SwaggerGeneratorException: Ambiguous HTTP method for action - SINOData.Controllers.OrderController.Success (SINOData). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable<ApiDescription> apiDescriptions, SchemaRepository schemaRepository)
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GeneratePaths(IEnumerable<ApiDescription> apiDescriptions, SchemaRepository schemaRepository)
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(string documentName, string host, string basePath)
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

看报错得知 action HomeController.Index 未明确标记 HttpMethod,这个action可以访问是因为全局路由所以可以访问。看到这个报错直接在报错对应的action上增加HttpMethod即可。

[ApiController]
[Route("/")]
public class HomeController : Controller
{
    [HttpGet]
    public ResponseVm Index()
    {
        return ResponseVm.Success();
    }
}

コメント:



(画像の文字列を入力して下さい)

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS