Nuggets 安装 Swashbuckle.AspNetCore
Startup Items Startup.cs registered swagger
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); #region Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v0.1.0", Title = "yaqa.Core API", Description = "框架说明文档", TermsOfService = "None", Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "yaqa.Core", Email = "[email protected]", Url = "" } }); }); #endregion }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } #region Swagger app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json" , " ApiHelp Vl " ); c.RoutePrefix = " " ; // path configuration, set to null, a direct access to the file, // path configuration, to blank, directly under the root domain (localhost: Access 8001) the file, note localhost: 8001 / swagger is less than the access, // this time to launchSettings.json in the "launchUrl": "swagger / index.html " removed, then direct access localhost: 8001 / index.html to }); #endregion app.UseHttpsRedirection (); app.UseMvc (); }
F5 to run the project, to the api / values interfaces, but I think you have to input the page directly to swagger / swagger. Too much trouble
Change the default path to swagger would not start every time you open rerouted.
Then add comments to the interface:
Notes on the interface code to write, read and add comments services. As the production of xml my default is the root directory, so the following comments to read xml read in accordance with the root directory path.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
#region Swagger
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v0.1.0", Title = "yaqa.Core API", Description = "框架说明文档", TermsOfService = "None", Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "yaqa.Core", Email = "[email protected]", Url = "" } }); });
//添加读取注释服务
var basePath = _hostingEnvironment.ContentRootPath;
var xmlPath = Path.Combine(basePath, "szApi.xml"); var entityXmlPath = Path.Combine(basePath, "Jum.Entity.xml"); //var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.XML"; c.IncludeXmlComments(xmlPath, true); c.IncludeXmlComments(entityXmlPath, true);
#endregion }
Press F5 to run you can see comments. (Written comments on the Model is the same)
Note Startup.cs paste whole code plus projects directly facilitate later reference:
public class Startup { private readonly IHostingEnvironment _hostingEnvironment; public Startup(IConfiguration configuration, IHostingEnvironment env) { //Configuration = configuration; _hostingEnvironment = env; var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddMvc().AddJsonOptions(options => { Options.SerializerSettings.DateFormatString = " YYYY the MM-dd-HH: mm: SS " ; // set the time format }); // Register Global services.AddMvc (O => { o.Filters.Add ( typeof (GlobalExceptionFilter) ); }); // registration profile services.AddOptions (); // . services.AddOptions () the configure <JwtAuthConfigModel> (Configuration.GetSection ( "JwtSettings")); services.Configure <the AppSetting> (Configuration.GetSection ( " AppSetting ")); Services.Configure <YZSetting> (Configuration.GetSection ( " YZSetting " )); // model validation binding properties, custom return format services.Configure <ApiBehaviorOptions> (Options => { options.InvalidModelStateResponseFactory = ActionContext => { // get a verification failure model field var errors = actionContext.ModelState .Where (E => e.Value.Errors.Count> 0 ) .Select (E => e.Value.Errors.First (). the ErrorMessage) . ToList (); var STR = String .join ( " | " , errors); // set the return content var Result = new new MessageModel { Success = to false , MSG = STR }; return new new BadRequestObjectResult (Result); }; }); // registrar services.AddTransient <IEntity, EntityService> (); /// / cache register //services.AddSingleton <IMemoryCache> (Factory => // { // var = Cache the MemoryCache new new (new new MemoryCacheOptions ()); // return Cache; // }); #region CORS services.AddCors (C => { C. AddPolicy ( " AllowAnyOrigin " , Policy => { policy.AllowAnyOrigin () // allows any source .AllowAnyMethod () // allow any manner .AllowAnyHeader () // allow any head .AllowCredentials();//允许cookie }); c.AddPolicy("AllowSpecificOrigin", policy => { policy.WithOrigins("http://xxxx:80") .WithMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .WithHeaders("authorization"); }); }); #endregion #region 注册Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1.1.0", Title = "sz WebAPI", Description = "框架集合", TermsOfService = "None", Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "Jumper", Email = "", Url = "" } }); //添加读取注释服务 var basePath = _hostingEnvironment.ContentRootPath; var xmlPath = Path.Combine(basePath, "szApi.xml"); var entityXmlPath = Path.Combine(basePath, "Jum.Entity.xml"); //xmlFile = $ var "{System.Reflection.Assembly.GetExecutingAssembly () GetName () the Name..} .XML"; c.IncludeXmlComments (XMLPath, to true ); c.IncludeXmlComments (entityXmlPath, to true ); // add a header to swagger authentication information var security = new new the Dictionary < String , the IEnumerable < String >> {{ " Bearer " , new new String [] {}},}; c.AddSecurityRequirement (security); // add must be a global information security, and AddSecurityDefinition method specifies the name of the program to be consistent, here is the Bearer. c.AddSecurityDefinition ( "Bearer " , new new ApiKeyScheme { the Description = " the JWT authorization (data will be transmitted in the request header) parameter structure: \ "the Authorization: Bearer token {} \" " , the Name = " the Authorization " , // JWT default parameter name In = " header " , // JWT Authorization default location to store information (request header) the Type = " the apiKey " }); }); #endregion } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // 注册中间件 app.UseMiddleware<JwtAuthorizationFilter>(); app.UseCors("AllowAnyOrigin"); // HTTP 重定向 app.UseHttpsRedirection(); app.UseMvc(); // 静态文件 app.UseStaticFiles(); #region Swagger app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1"); }); #endregion } }