【.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文档配置

相关推荐
向宇it1 小时前
【unity小技巧】unity 什么是反射?反射的作用?反射的使用场景?反射的缺点?常用的反射操作?反射常见示例
开发语言·游戏·unity·c#·游戏引擎
九鼎科技-Leo2 小时前
什么是 WPF 中的依赖属性?有什么作用?
windows·c#·.net·wpf
Heaphaestus,RC3 小时前
【Unity3D】获取 GameObject 的完整层级结构
unity·c#
baivfhpwxf20233 小时前
C# 5000 转16进制 字节(激光器串口通讯生成指定格式命令)
开发语言·c#
直裾3 小时前
Scala全文单词统计
开发语言·c#·scala
ZwaterZ5 小时前
vue el-table表格点击某行触发事件&&操作栏点击和row-click冲突问题
前端·vue.js·elementui·c#·vue
惜.己6 小时前
Jmeter中的断言(二)
测试工具·jmeter·1024程序员节
dot.Net安全矩阵7 小时前
.NET 通过模块和驱动收集本地EDR的工具
windows·安全·web安全·.net·交互
zls3653657 小时前
.NET开源实时应用监控系统:WatchDog
.net
djk88887 小时前
.net将List<实体1>的数据转到List<实体2>
数据结构·list·.net