【.Net】【C#】Program.cs通用代码模板

【.Net】【C#】Web Core Api 通用代码模板

常用NuGet

Microsoft.Extensions.Logging.Log4Net.AspNetCore

Flurl

Flurl.Http

Program.cs

c# 复制代码
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Swashbuckle.AspNetCore.SwaggerUI;

namespace model
{
    /// <summary>
    ///
    /// </summary>
    public class Program
    {
        public static void Main(string[] args)
        {
            #region 自定义配置
            var builder = WebApplication.CreateBuilder(args);

            builder
                .Services.AddControllers()
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    //配置返回Json大小写格式与Model一致
                    //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    //统一设置日期格式
                    //options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
                });
            builder.Services.AddControllers();
            //添加全局异常处理机制
            builder.Services.AddMvc(option =>
            {
                option.Filters.Add<ExceptionHandler>();
            });

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc(
                    "v1",
                    new OpenApiInfo
                    {
                        Version = "v1",
                        Title = AppSettingsHelper.GetSetting("AppName"),
                        Description = $"API描述,v1版本",
                    }
                );
                var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                //IncludeXmlComments 第二参数 true 则显示 控制器 注释
                options.IncludeXmlComments(
                    Path.Combine(AppContext.BaseDirectory, xmlFilename),
                    true
                );
                #region 启用swagger验证功能
                options.AddSecurityDefinition(
                    "Authorization",
                    new OpenApiSecurityScheme()
                    {
                        Description = "在下框中输入请求头中需要添加授权token:Authorization",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Type = SecuritySchemeType.ApiKey,
                        BearerFormat = "Authorization",
                        Scheme = "Authorization",
                    }
                );

                options.AddSecurityRequirement(
                    new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.SecurityScheme,
                                    Id = "Authorization",
                                },
                            },
                            Array.Empty<string>()
                        },
                    }
                );

                #endregion
            });

            //校验配置
            builder
                .Services.AddControllers()
                .ConfigureApiBehaviorOptions(options =>
                {
                    //options.SuppressConsumesConstraintForFormFileParameters = true;
                    //options.SuppressInferBindingSourcesForParameters = true;
                    options.SuppressModelStateInvalidFilter = true;
                    options.SuppressMapClientErrors = true;
                    options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "/error";
                });
            var app = builder.Build();

            app.UseSwagger();
            app.UseSwaggerUI(m => m.DocExpansion(DocExpansion.None));
            //app.UseHttpsRedirection();
            //跨域
            //app.UseCors("Cors");
            // 设置允许所有来源跨域
            app.UseCors(builder =>
            {
                builder
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .SetPreflightMaxAge(TimeSpan.FromSeconds(2000000));
            });
            //app.UseAuthentication();
            //app.UseAuthorization();


            app.MapControllers();

            #region 配置中心刷新配置
            //new ConnStr();
            #endregion

            app.Run();
            #endregion
        }
    }

    /// <summary>
    /// 异常拦截器
    /// </summary>
    public class ExceptionHandler : IExceptionFilter
    {
        /// <summary>
        /// 异常拦截器
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled) //如果异常没有被处理过
            {
                Exception ex = context.Exception;
                //Logger.Log(ex.ToString(), Level.ERROR);
                var request = context.HttpContext.Request;
                string url = request.Path + context.HttpContext.Request.QueryString;
                //var ParamPost = JsonConvert.SerializeObject(request.Method == "POST" ? request.Form : "");
                //Logger.Log($"url={url},param={ParamPost}");
                //全局错误返回
                //context.Result = new JsonResult(ResponseUtil.Error(ex.Message))
                //{
                //    StatusCode = (int)HttpStatusCode.OK
                //};
                Logger.Log(
                    $"url={url},ex.Message={ex.Message},ex.StackTrace={ex.StackTrace}",
                    Level.ERROR
                );
                //全局错误返回
                context.Result = new OkObjectResult(ResponseModelInfo.SysError(ex.ToString()));
                context.ExceptionHandled = true;
            }
        }
    }
}

appsettings.json

json 复制代码
{
  "AppName": "样例",
  "Kestrel": {
    "Endpoints": {
      "Http": { "Url": "http://*:9000/" }
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

log4net.config

xml 复制代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<log4net>
		<appender name="RollingLogFileAppender"
				  type="log4net.Appender.RollingFileAppender">
			<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
			<file value="logs\" />
			<datePattern value="'info-'yyyy-MM-dd'.log'"/>
			<staticLogFileName value="false"/>
			<appendToFile value="true"/>
			<rollingStyle value="Composite"/>
			<maxSizeRollBackups value="10"/>
			<maximumFileSize value="30MB"/>
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern
					value="%date [%thread][%-5level][%logger][%line] %message%newline"/>
			</layout>
		</appender>
		<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern value="%date [%thread][%-5level][%logger][%line] %message%newline" />
			</layout>
		</appender>
		<root>
			<level value="INFO"/>
			<appender-ref ref="RollingLogFileAppender"/>
			<appender-ref ref="ConsoleAppender" />
		</root>
	</log4net>
</configuration>

VS2022 swagger文档配置

相关推荐
DC妙妙屋28 分钟前
10.24.2024刷华为OD C题型(四) -- 对象list按照多个属性排序
1024程序员节
无敌最俊朗@39 分钟前
unity3d————三角函数练习题
开发语言·学习·unity·c#·游戏引擎
bitenum1 小时前
qsort函数的学习与使用
c语言·开发语言·学习·算法·visualstudio·1024程序员节
Crazy Struggle1 小时前
.NET 实现的零部件离散型 MES+WMS 系统
wms·.net·mes·制造管理系统
EmotionFlying2 小时前
(11)(2.1.6) Hobbywing DroneCAN ESC(一)
copter·ardupilot·1024程序员节·电调和电机
伏飞而行2 小时前
六、元素应用CSS的习题
1024程序员节
月巴月巴白勺合鸟月半2 小时前
C#版的有道智云对话接口
开发语言·c#
浪里个浪的10242 小时前
【C#】编写计算机选课程序
开发语言·c#
idealzouhu2 小时前
Spring Boot 实现文件上传下载功能
java·spring boot·1024程序员节
sudo_Ene3 小时前
Isaac Sim Docker 部署并使用过程记录
笔记·学习·docker·1024程序员节·isaacsim