首页后端开发ASP.NET【愚公系列】2023年02月 .NET/C#知识点-.NET Core配置文件详解

【愚公系列】2023年02月 .NET/C#知识点-.NET Core配置文件详解

时间2023-03-24 17:30:28发布访客分类ASP.NET浏览1115
导读:文章目录前言1.IP和端口2.域名3.通用软件说明一、.NET Core配置文件详解1.launchSettings.json2.appsettings.json2.1 说明2.2 读取3.Program.cs3.1 UseUrls3.2...

文章目录

  • 前言
    • 1.IP和端口
    • 2.域名
    • 3.通用软件说明
  • 一、.NET Core配置文件详解
    • 1.launchSettings.json
    • 2.appsettings.json
      • 2.1 说明
      • 2.2 读取
    • 3.Program.cs
      • 3.1 UseUrls
      • 3.2 UseKestrel
      • 3.3 app.Urls.Add
  • 总结

前言

1.IP和端口

任何一个系统进程都是同个IP和端口号的组合来定位的。网站其实也是进程之一,网站的访问,都是通过服务器的IP和端口号的组合来实现访问的,比如:127.0.0.1:8080,浏览器访问就是:

`http://127.0.0.1:8080,https://127.0.0.1:8080`

2.域名

域名(英语:Domain Name),又称网域,是由一串用点分隔的名字组成的Internet上某一台计算机或计算机组的名称,用于在数据传输时对计算机的定位标识(有时也指地理位置)。

由于IP地址具有不方便记忆并且不能显示地址组织的名称和性质等缺点,人们设计出了域名,并通过网域名称系统(DNS,Domain Name System)来将域名和IP地址相互映射,使人更方便地访问互联网,而不用去记住能够被机器直接读取的IP地址数串。

www.baidu.com=127.0.0.1:8080

具体域名和IP和端口是对应的,不能少端口,一般IP默认端口是80

3.通用软件说明

很多通用的软件都有自己默认端口:

  • FTP:21
  • SSH:22
  • MYSQL:3306
  • DNS:53
  • HTTP:80
  • POP3:109
  • Https:443

1.公认端口(Well Known Ports):从0到1023,它们紧密绑定于一些服务。通常这些端口的通讯明确表明了某种服务的协议。例如:80端口实际上总是HTTP通讯。

2.注册端口(Registered Ports):从1024到49151。它们松散地绑定于一些服务。也就是说有许多服务绑定于这些端口,这些端口同样用于许多其它目的。例如:许多系统处理动态端口从1024左右开始。

3.动态和/或私有端口(Dynamic and/or Private Ports):从49152到65535。无服务分配在这些端口。

本文主要是介绍.NET Core站点端口修改方式:

  • launchSettings.json
  • appsettings.json
  • Program.cs

一、.NET Core配置文件详解

1.launchSettings.json

LaunchSettings.json文件,仅仅只是在本地的电脑上使用。这也就是意味着,当我们发布ASP.NET Core应用程序到生产环境的时候,这个文件是不需要的。

launchSettings.json配置说明:

  • launchBrowser :一个布尔类型的开关,表示应用程序的时候是否自动启动浏览器
  • launchUrl:如果launchBrowser被设置为true,浏览器采用的初始化路径通过该属性进行设置。
  • environmentVariables:该属性用来设置环境变量。ASP.NET Core应用中正是利用这样一个环境变量来表示当前的部署环境。多环境的配置可以通过ASPNETCORE_ENVIRONMENT切换。
  • commandName:启动当前应用程序的命令类型,有效的选项包括IIS、IISExpress和Project,前三个选项分别表示采用IIS、IISExpress和指定的可执行文件(.exe)来启动应用程序。如果我们使用dotnet run命令来启动程序,对应Profile的启动命名名称应该设置为Project。
  • applicationUrl:应用程序采用的URL列表,多个URL之间采用分号(“;”)进行分隔。

LaunchSettings.json配置案例:

{

  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {

    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {

      "applicationUrl": "http://localhost:20458",
      "sslPort": 44337
    }

  }
,
  "profiles": {

    "http": {

      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:5289",
      "environmentVariables": {

        "ASPNETCORE_ENVIRONMENT": "Development"
      }

    }
,
    "https": {
    
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:7002;
http://localhost:5289",
      "environmentVariables": {

        "ASPNETCORE_ENVIRONMENT": "Development"
      }

    }
,
    "IIS Express": {

      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {

        "ASPNETCORE_ENVIRONMENT": "Development"
      }

    }

  }

}

2.appsettings.json

2.1 说明

首先在 ASP .NET Core 项目当中添加一个appsettings.json(默认都有该文件)文件,可以包含如下两个文件:

  • appsettings.Development.json:开发环境
  • appsettings.Production.json:生产环境

在appsettings.json里也可以修改默认的端口,主要是配置Kestrel节点下终结点的默认url,片段代码如下:

"Kestrel":{

  "Endpoints": {

    "Https": {

      "Url": "https://*:9001"
    }
,
    "Http": {

      "Url": "http://*:9000"
    }

  }

}
    

2.2 读取

1、直接读取

var Default = builder.Configuration["Logging:Loglevel:Default"];

2、模型绑定

定义模型

public class SectionModel
{
    
    //绑定时只会绑定公有属性,不会绑定字段
    public const string SectionName = "Position";

    public string Title {
     get;
     set;
 }

    public string Name {
     get;
     set;
 }

}

设置配置文件

"Position":{

    "Title":"Editor",
    "Name":"Jos"
}
    

绑定

var model = new SectionModel();
    
builder.Configuration.GetSection(SectionModel.SectionName).Bind(model);
    //这样就拿到了配置
//当然也可以这么写
builder.Configuration.GetSection(SectionModel.SectionName).GetSectionModel>
    ();
    

3、IOptions使用

配置

builder.Services.ConfigureSectionModel>
    (builder.Configuration.GetSection(SectionModel.SectionName));
    

使用

using Microsoft.AspNetCore.Mvc;
    
using Microsoft.Extensions.Options;
    
using System.Reflection;


namespace WebApiTest.Controllers
{

    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {

        private static readonly string[] Summaries = new[]
        {

        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    }
    ;
    

        private readonly ILoggerWeatherForecastController>
     _logger;
    
        private readonly IOptionsSectionModel>
     _model;
    

        public WeatherForecastController(ILoggerWeatherForecastController>
     logger, IOptionsSectionModel>
 model)
        {
    
            _logger = logger;
    
            _model = model;

        }
    

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerableWeatherForecast>
 Get()
        {
    
            var Title = _model.Value.Title;
    
            return Enumerable.Range(1, 5).Select(index =>
 new WeatherForecast
            {

                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            }
    )
            .ToArray();

        }

    }

}
    

如果要及时响应修改,则将上述的IOptions改为IOptionsSnapshot。

4、GetValue

var number = builder.Configuration.GetValuestring>
    ("RedisUrl", "99");
    //找不到的话默认99

5、GetSection

var selection = builder.Configuration.GetSection("Position");

if (selection.Exists())
{
    
    var children = selection.GetChildren();

    foreach (var subSection in children)
    {

        //subSection.Key  selection[key]
    }

}
    

3.Program.cs

Program.cs可以覆盖前面两个配置,不过不支持代码中配置,只是作于说明:

3.1 UseUrls

这种方式可以设置单个和多个,具体代码设置如下

builder.WebHost.UseUrls("https://*:9001");
//单个设置
builder.WebHost.UseUrls(new[] {
 "http://*:9000", "https://*:9001" }
    );
    

3.2 UseKestrel

利用webhost下的组件配置。

builder.WebHost.ConfigureKestrel(options =>
     options.ListenLocalhost(8090, opts =>
     opts.Protocols = HttpProtocols.Http1));
    

3.3 app.Urls.Add

这个是.NET6以上版本新增加的方式,利用中间件添加。

app.Urls.Add("http://localhost:9000");
    

总结

当然还可以用命令进行配置启动,比如命令的方式来修改启动的端口号,缺点是每次启动都得添加。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

jsonaspappsettingscsip

若转载请注明出处: 【愚公系列】2023年02月 .NET/C#知识点-.NET Core配置文件详解
本文地址: https://pptw.com/jishu/272.html
正式开始学习ASP.NET Core 6 Razor Pages 介绍 安全攻防 | MSF生成Payload方式总结

游客 回复需填写必要信息