CommonUtils.Core/SwaggerUtil.cs

(开头部分) 2KB

这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace CommonUtils
{
    /// <summary>
    /// https://blog.csdn.net/fromfire2/article/details/102605174
    /// </summary>
    public static class SwaggerUtil
    {
        public static void AddMySwagger(this IServiceCollection services)
        {
            services.AddRazorPages();

            services.AddControllers()
            //原生Json服务中文、变量、注释支持差,这里切换为Newtonsoft提供的Json服务,必须引用Microsoft.AspNetCore.Mvc.NewtonsoftJson,引用Newtonsoft.Json此处无效
            .AddNewtonsoftJson(options =>
            {
                //保持Json属性/变量大小写
                options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //如字段为null值,该字段不会返回到前端
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            //生成swagger
            services.AddSwaggerGen(options =>
            {
                //设置swagger标题
                options.SwaggerDoc("doc", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "@Title", Version = "v1.0" });
                //添加接口注释
                options.IncludeXmlComments("comment.xml");
            });
        }

        public static void UseMySwagger(this IApplicationBuilder app)
        {
            app.UseStaticFiles();
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });
            app.UseSwagger();
            app.UseSwaggerUI(options => options.SwaggerEndpoint("/swagger/doc/swagger.json", null));
        }

        //添加Header到http请求
        public static void AddHeader(this SwaggerGenOptions options, string name)
        {
            var id = "添加Header到http请求";
            //添加Authorize按钮
            options.AddSecurityDefinition(id, new OpenApiSecurityScheme()
后面还有 14 行代码,解锁后查看完整代码

24 小时内免费解锁 3 个项目,之后 1 算力/个。 规则说明

AI 解读 AI

登录后可用,每次 10 算力,解读结果公开显示在下面。

还没有人解读过这个文件。