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

news/2024/5/19 23:40:03 标签: .netcore

效果图:
在这里插入图片描述

1.新建.net core web api项目

选择src文件夹==》添加==》新建项目
在这里插入图片描述
输入框搜索:web api ==》选择ASP.NET Core Web API
在这里插入图片描述
输入项目名称、选择位置为项目的 src文件夹下
在这里插入图片描述
我的项目是net 7.0版本,实际选择请看自己的项目规划
在这里插入图片描述

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

需要安装NuGet程序依赖包:Newtonsoft.Json、Serilog.AspNetCore、Serilog.Sinks.Async、Serilog.Sinks.File
在这里插入图片描述
Program文件代码如下:

    /// <summary>
    /// 
    /// </summary>
    public class Program
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        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();
            }

        }

        /// <summary>
        /// 载入Startup配置、以及新增日志
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        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文件代码如下

/// <summary>
/// 
/// </summary>
public class Startup
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="configuration"></param>
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    /// <summary>
    /// 
    /// </summary>
    public IConfiguration Configuration { get; }

    /// <summary>
    /// This method gets called by the runtime. Use this method to add services to the container.
    /// </summary>
    /// <param name="services"></param>
    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();
    }

    /// <summary>
    /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    /// </summary>
    /// <param name="app"></param>
    /// <param name="env"></param>
    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文档
在这里插入图片描述

4.在Controllers控制器写接口

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

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

     /// <summary>
     /// 获取请求客户端的ip地址
     /// </summary>
     /// <returns></returns>
     [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的操作下拉框里改成启动==>点击应用按钮==>点击确定按钮
在这里插入图片描述
然后按ctrl+F5运行
在这里插入图片描述
电脑桌面右下角有iis的图标
在这里插入图片描述

6.打包发布

选择新建的web api项目==》点击 发布
在这里插入图片描述
配置选择"文件夹"如下
在这里插入图片描述
文件夹位置 路径默认不管
在这里插入图片描述
更改配置如下
在这里插入图片描述
然后点击发布按钮在这里插入图片描述

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

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


http://www.niftyadmin.cn/n/5231382.html

相关文章

webWorker解决单线程中的一些小问题和性能优化

背景 js是单线程这是大家都知道&#xff0c;为了防止多个线程同时操作DOM&#xff0c;这个导致一个复杂的同步问题。比如&#xff0c;假定JavaScript同时有两个线程&#xff0c;一个线程在某个DOM节点上添加内容&#xff0c;另一个线程删除了这个节点&#xff0c;这时浏览器应…

Windows 安装redis,设置开机自启动

Windows 安装redis,设置开机自启动 文章目录 Windows 安装redis,设置开机自启动下载, 解压到指定目录设置redis密码启动redis服务端停止redis服务端设置自启动 下载, 解压到指定目录 官网地址: https://redis.io/ 安装包下载地址: https://github.com/tporadowski/redis/relea…

Hdoop学习笔记(HDP)-Part.15 安装HIVE

十五、安装HIVE 1.配置MetaStore 利用ambari创建的MySQL作为MetaStore&#xff0c;创建用户hive及数据库hive mysql -uroot -p CREATE DATABASE hive; CREATE USER hive% IDENTIFIED BY lnydLNsy115; GRANT ALL ON hive.* TO hive%; FLUSH PRIVILEGES;2.安装 在服务中添加H…

山西电力市场日前价格预测【2023-12-02】

日前价格预测 预测说明&#xff1a; 如上图所示&#xff0c;预测明日&#xff08;2023-12-02&#xff09;山西电力市场全天平均日前电价为373.22元/MWh。其中&#xff0c;最高日前电价为765.50元/MWh&#xff0c;预计出现在17:45。最低日前电价为187.48元/MWh&#xff0c;预计…

微信小程序自定义tabBar简易实现

文章目录 1.app.json设置custom为true开启自定义2.根目录创建自定义的tab文件3.app.js全局封装一个设置tabbar选中的方法4.在onshow中使用选中方法最终效果预览 1.app.json设置custom为true开启自定义 2.根目录创建自定义的tab文件 index.wxml <view class"tab-bar&quo…

AutoDL 使用记录

AutoDL 使用记录 1.租用新实例 创建实例需要依次选择&#xff1a;计费方式 → \to → 地区 → \to → GPU型号与数量 → \to → 主机 注意事项&#xff1a; 主机 ID&#xff1a;一个吉利的机号有助于炼丹成功价格&#xff1a;哪个便宜选哪个最高 CUDA 版本&#xff1a;影响…

Javase | Java工具类、(SSM)各种依赖的作用

目录: Java工具类&#xff1a;日期工具类文件上传工具类 短信工具类验证码工具类邮件工具类代码生成器 (SSM)各种依赖的作用&#xff1a;spring-context 依赖&#xff1a;spring-context-supprt 依赖&#xff1a;spring-tx 依赖:mysql-connector-java 依赖&#xff1a;spring-j…

HNU 练习八 结构体编程题5. 火星人足球赛

【问题描述】 火星人足球赛的比赛规则与地球人的比赛规则有些非常相似&#xff0c;比如严重犯规&#xff0c;将被给予黄牌警告&#xff0c;特别严重的犯规&#xff0c;将给予红牌直接罚下&#xff0c;如果有人得到第2张黄牌&#xff0c;则自动获得红牌罚下&#xff0c;比赛同样…