【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布

效果图:
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第1张图片

1.新建.net core web api项目

选择src文件夹==》添加==》新建项目
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第2张图片
输入框搜索:web api ==》选择ASP.NET Core Web API
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第3张图片
输入项目名称、选择位置为项目的 src文件夹下
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第4张图片
我的项目是net 7.0版本,实际选择请看自己的项目规划
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第5张图片

2.处理Program入口文件引入日志和新建Startup.cs

需要安装NuGet程序依赖包:Newtonsoft.Json、Serilog.AspNetCore、Serilog.Sinks.Async、Serilog.Sinks.File
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第6张图片
Program文件代码如下:

    /// 
    /// 
    /// 
    public class Program
    {
        /// 
        /// 
        /// 
        /// 
        public static int Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
#if DEBUG
                 .MinimumLevel.Debug()
#else
                .MinimumLevel.Information()
#endif
                 .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.Async(c => c.File("Logs/logs.txt", rollingInterval: RollingInterval.Hour))
#if DEBUG
                 .WriteTo.Async(c => c.Console())
#endif
                 .CreateLogger();
            // Wrap creating and running the host in a try-catch block
            try
            {
                Log.Information("Starting host");

                CreateHostBuilder(args).Build().Run();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }

        }

        /// 
        /// 载入Startup配置、以及新增日志
        /// 
        /// 
        /// 
        public static IHostBuilder CreateHostBuilder(string[] args) =>
           Host.CreateDefaultBuilder(args)
               .UseSerilog()
               .ConfigureWebHostDefaults(webBuilder =>
               {
                   var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();


                   var url = configuration["Urls"];
                   webBuilder.UseUrls(url);
                   webBuilder
#if !DEBUG
                    .UseEnvironment("ASPNETCORE_HOSTINGSTARTUPASSEMBLIES")
#endif
                   .UseStartup<Startup>();
               });

    }

Startup文件代码如下

/// 
/// 
/// 
public class Startup
{
    /// 
    /// 
    /// 
    /// 
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    /// 
    /// 
    /// 
    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.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "这里替换成你新建webApi项目的名称", Version = "v1" });
            var basePath = PlatformServices.Default.Application.ApplicationBasePath;
            var XmlPath = Path.Combine(basePath, "这里替换成你新建webApi项目的名称.xml");//此处生成xml文档
            c.IncludeXmlComments(XmlPath);
        });
        //处理跨域问题
        services.AddCors(option => {
            option.AddPolicy("any", policy =>
            {
                policy.SetIsOriginAllowed(_ => true)   //允许所有客户端地址请求
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
            });
        });
        services.AddMemoryCache();
        services.AddHttpContextAccessor();
    }

    /// 
    /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    /// 
    /// 
    /// 
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseSerilogRequestLogging();

        app.UseRouting();
        app.UseCors("any");//处理跨域问题
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "这里替换成你新建webApi项目的名称 v1"));
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers().RequireCors("any");
        });
    }
}

appsettings.json代码如下

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "Urls": "http://*:44375;",
  "AllowedHosts": "*"
 
}

3.处理launchSettings.json文件,使本地启动项目时是以iis运行

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:44375",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "SkyAPM.Agent.AspNetCore"
      }
    },
    "这里替换成你新建webApi项目的名称": {
      "commandName": "Project",
      "launchBrowser": true,
      "dotnetRunMessages": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:44375",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "SkyAPM.Agent.AspNetCore"
      }
    }
  }
}

处理在文件里生成xml文档
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第7张图片

4.在Controllers控制器写接口

在项目的Controllers文件夹下,新建一个xxxxController.cs

 /// 
 /// 名称
 /// 
 [ApiController]
 [Route("outApi/[controller]/[action]")]
 public class xxxxController : ControllerBase
 {
     private readonly IHttpContextAccessor _httpContextAccessor;
     /// 
     /// 
     /// 
     public questionController(IHttpContextAccessor httpContextAccessor)
     {
         _httpContextAccessor = httpContextAccessor;
     }

     /// 
     /// 获取请求客户端的ip地址
     /// 
     /// 
     [HttpGet]
     public async Task<string> testIP()
     {

         Log.Information("IP:" + Request.HttpContext.Connection.RemoteIpAddress.ToString() + "InputQuestion入参:" );
         string ipAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress?.ToString();
         return ipAddress;
     }
 }

5.设置项目启动项并运行

选择解决方案右键==>选择 配置启动项目==>弹窗里选择 多个启动项目==》把新建的web api的操作下拉框里改成启动==>点击应用按钮==>点击确定按钮
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第8张图片
然后按ctrl+F5运行
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第9张图片
电脑桌面右下角有iis的图标
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第10张图片

6.打包发布

选择新建的web api项目==》点击 发布
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第11张图片
配置选择"文件夹"如下
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第12张图片
文件夹位置 路径默认不管
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第13张图片
更改配置如下
【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第14张图片
然后点击发布按钮【.net core 7】新建net core web api并引入日志、处理请求跨域以及发布_第15张图片

7.部署到centos服务器,请参考我的另外一篇文章

【liunx配置服务自启动】liunx系统设置net Core程序开机自启动服务 centos系统

你可能感兴趣的:(.netcore)