我将我的asp.net核心应用程序更新为v3.1,将SwaggerForv5.04RC更新为v5.0,一切都停止了。API正在工作,但我无法生成swagger文件,而且我能够。
这是我的装腔作势。
public static class SwaggerConfig
{
[Obsolete]
public static void ConfigureSWAGGER(this IServiceCollection serviceColletion)
{
if (serviceColletion == null)
{
throw new ArgumentNullException(nameof(serviceColletion));
}
// Use http://localhost:5000/swagger/ui/index to inspect API docs
serviceColletion.AddSwaggerGen(x =>
{
x.SwaggerDoc(Constatns.BackofficeSwaggerGroup, new OpenApiInfo { Title = "Portal Nekretnine - Backoffice", Version = Constatns.BackofficeSwaggerGroup });
x.SwaggerDoc(Constatns.PublicSwaggerGroup, new OpenApiInfo { Title = "Portal Nekretnine - Public", Version = Constatns.PublicSwaggerGroup });
// This code allow you to use XML-comments
string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
{
x.IncludeXmlComments(xmlPath);
}
x.AddSecurityDefinition
(
"Bearer",
new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter token into the field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
}
);
});
}
public static void UseSWAGGER(this IApplicationBuilder applicationBuilder)
{
// Enable middleware to serve generated Swagger as a JSON endpoint.
applicationBuilder.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
applicationBuilder.UseSwaggerUI(x =>
{
x.SwaggerEndpoint($"/swagger/{Constatns.BackofficeSwaggerGroup}/swagger.json", "Portal Nekretnine - Backoffice");
x.SwaggerEndpoint($"/swagger/{Constatns.PublicSwaggerGroup}/swagger.json", "Portal Nekretnine - Public");
});
}
}这是我的startup.cs
public partial class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
if (env.IsDevelopment())
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile($"appsettings.development.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
else
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.AddJsonFile($"appsettings.production.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
}
// This method gets called by the runtime. Use this method to add services to the container.
[System.Obsolete]
public void ConfigureServices(IServiceCollection services)
{
SetServices(services);
services.ConfigureCOMPRESSION();
//disable built in model validator
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddMvcCore(options =>
{
//Validate model
options.Filters.Add(typeof(ValidateModelAttribute));
// Add "Cache-Control" header
options.Filters.Add(typeof(CacheControlFilter));
// Add custom binder provider for mapping json object form multipart/form-data
options.ModelBinderProviders.Insert(0, new JsonModelBinderProvider());
})
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddApiExplorer();
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
options.SerializerSettings.Converters.Add(new JsonDateConverter());
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
#if DEBUG
options.SerializerSettings.Formatting = Formatting.Indented;
#else
options.SerializerSettings.Formatting = Formatting.None;
#endif
});
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.ConfigureCookieAuthentication();
services.ConfigureAUTH(Configuration);
services.ConfigureCORS();
services.ConfigureSWAGGER();
services.AddSwaggerGenNewtonsoftSupport(); // explicit opt-in - needs to be placed after AddSwaggerGen()
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseRouting();
app.UseCOMPRESSION();
app.UseAUTH();
app.UseAuthorization();
app.UseCORS();
app.UseSWAGGER();
app.UseHttpStatusCodeExceptionMiddleware();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}还有一个我的控制器的例子:
[ApiController]
public class SecurityController : ControllerBase
{
[ApiExplorerSettings(GroupName = Constatns.PublicSwaggerGroup)]
[SwaggerOperation(OperationId = "registerVisitor")]
[HttpPost("api/register/visitor")]
[ValidateModel]
[AllowAnonymous]
[ProducesResponseType((int)HttpResponseType.OK, Type = typeof(TokenResponse))]
[ProducesResponseType((int)HttpResponseType.BadRequest)]
[Produces("application/json")]
public async Task<TokenResponse> RegisterVisitor([FromBody] RegisterVisitorRequest data)
{}
}我得到的错误是:
失败: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware1在执行请求时发生了一个未处理的异常。Microsoft.OpenApi.Writers.OpenApiJsonWriter..ctor(System.IO.TextWriter)'.:System.MissingMethodException:方法未找到:'Void System.MissingMethodException在Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.RespondWithSwaggerJson(HttpResponse响应下,在System.Runtime.CompilerServices.AsyncMethodBuilderCore.StartTStateMachine ( Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.RespondWithSwaggerJson(HttpResponse响应),OpenApiDocument (在Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext ),( ISwaggerProvider swaggerProvider(在Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext上下文))在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文中)( Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware中间件、HttpContext context、Task任务)
thnx
发布于 2020-01-30 21:11:56
经过几个小时的深入研究,我发现使用Microsoft.OpenApi 1.2.0-预览与.net内核3.1和swagger v5并不紧密,使用微软OpenApi的1.1.4版本
发布于 2020-09-06 11:16:44
我能够用以下方法作出答复:
第一,
1-Install-Package Swashbuckle.AspNetCore其次,在Startup.cs中插入以下方法:
private static void ConfigureSwagger(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
}第三,在ConfigureServies方法中调用ConfigureSwagger方法如下:
ConfigureSwagger(services)
第四,在配置方法中插入这些代码,
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});最后,右键单击您的API,在调试选项前,在浏览器启动选项前面,删除文本框的内容,并在文本框中写入swagger。
运行项目
锁得好。
enter code here
发布于 2021-01-07 12:12:10
使用Swashbuckle.AspNetCore而不是Swashbuckle.AspNetCore.Swagger解决了这个问题。
https://stackoverflow.com/questions/59992762
复制相似问题