[英]ASP.NET Core Web API - JSON Ignore not working in Core-6 Swagger
In my ASP.NET Core 6 Web API, I am implementing Json Ignore in Swagger.在我的 ASP.NET Core 6 Web API 中,我正在 Swagger 中实现 Json Ignore。
I have this code:我有这个代码:
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() ||
context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any();
if (!hasAuthorize)
return;
operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized - not authenticated" });
operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden - not authorized" });
var bearerScheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" },
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
};
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
[bearerScheme] = new [] {""}
}
};
}
}
Then I did the configuration in Program.cs
as shown here:然后我在
Program.cs
中进行了配置,如下所示:
var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;
var environment = builder.Environment;
var swaggerDocOptions = new SwaggerDocOptions();
builder.Services.AddControllers().AddNewtonsoftJson(op => op.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore);
builder.Services.AddSwaggerGen();
builder.Services.AddOptions<SwaggerGenOptions>()
.Configure<IApiVersionDescriptionProvider>((swagger, service) =>
{
foreach (ApiVersionDescription description in service.ApiVersionDescriptions)
{
swagger.SwaggerDoc(description.GroupName, new OpenApiInfo
{
Title = swaggerDocOptions.Title,
Version = description.ApiVersion.ToString(),
Description = swaggerDocOptions.Description,
TermsOfService = new Uri("https://myapp.com/LICENSE.md"),
Contact = new OpenApiContact
{
Name = swaggerDocOptions.Organization,
Email = swaggerDocOptions.Email
},
License = new OpenApiLicense
{
Name = "MIT",
Url = new Uri("https://myapp.com/kkj")
}
});
}
var security = new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[0]}
};
swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT"
});
swagger.OperationFilter<AuthorizeCheckOperationFilter>();
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
swagger.IncludeXmlComments(xmlPath);
});
// Register and Configure API versioning
builder.Services.AddApiVersioning(options =>
{
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ReportApiVersions = true;
});
// Register and configure API versioning explorer
builder.Services.AddVersionedApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
And finally, I apply it in the model class like this:最后,我将它应用到模型类中,如下所示:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MobileNumber { get; set; }
[JsonIgnore]
public bool? IsPasswordChanged { get; set; }
[JsonIgnore]
public bool? IsDeleted { get; set; }
}
I expected that IsPasswordChanged
and IsDeleted
shouldn't appear in Swagger, but they still appear despite the JSON Ignore.我预计
IsPasswordChanged
和IsDeleted
不应该出现在 Swagger 中,但尽管 JSON Ignore,它们仍然会出现。
Where have I missed it and how do I correct this?我在哪里错过了它,我该如何纠正?
Thank you谢谢
There is the [OpenApiIgnore]
attribute in the NSwag.Annotations
namespace for AspNetCore. AspNetCore 的
NSwag.Annotations
命名空间中有[OpenApiIgnore]
属性。 It appears to work on a class or a method and excludes them from the generated Swagger document.它似乎适用于类或方法,并将它们从生成的 Swagger 文档中排除。 You will need to include the
NSwag.AspNetCore
package from NuGet.您将需要包含来自 NuGet 的
NSwag.AspNetCore
包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.