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

相关推荐
向宇it7 小时前
【从零开始入门unity游戏开发之——C#篇25】C#面向对象动态多态——virtual、override 和 base 关键字、抽象类和抽象方法
java·开发语言·unity·c#·游戏引擎
数据的世界017 小时前
.NET开发人员学习书籍推荐
学习·.net
向宇it8 小时前
【从零开始入门unity游戏开发之——C#篇24】C#面向对象继承——万物之父(object)、装箱和拆箱、sealed 密封类
java·开发语言·unity·c#·游戏引擎
paixiaoxin9 小时前
CV-OCR经典论文解读|An Empirical Study of Scaling Law for OCR/OCR 缩放定律的实证研究
人工智能·深度学习·机器学习·生成对抗网络·计算机视觉·ocr·.net
yaosheng_VALVE12 小时前
探究全金属硬密封蝶阀的奥秘-耀圣控制
运维·eclipse·自动化·pyqt·1024程序员节
dami_king12 小时前
SSH特性|组成|SSH是什么?
运维·ssh·1024程序员节
坐井观老天13 小时前
在C#中使用资源保存图像和文本和其他数据并在运行时加载
开发语言·c#
pchmi15 小时前
C# OpenCV机器视觉:模板匹配
opencv·c#·机器视觉
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭17 小时前
C#都可以找哪些工作?
开发语言·c#
19004317 小时前
.NET重点
.net