2024年10月 工作技术

104 阅读5分钟

15日

服务器安装 .net core 6

  1. ssh链接linux

  2. 退出(base环境)conda deactivate

  3. 【.Net6极速部署Linux(.Net Core发布技巧/Linux基础教学)】 www.bilibili.com/video/BV1pS…

    • Microsoft PPA命令配置:wget packages.microsoft.com/config/ubun…

    • sudo dpkg -i packages-microsoft-prod.deb 

    • sudo apt-get update

    • 安装.net core运行时: sudo apt install aspnetcore-runtime-6.0

    • 启动dotnet服务: nohup dotnet AuthServer.Host.dll &

  4. 守护进程防止 shell 关闭

    • nohup dotnet xxx.dll

服务器安装 mysql

【Ubuntu下安装MySQL数据库】 www.bilibili.com/video/BV12q…

sudo apk update
sudo apk install mysql-server
yes
sudo mysql_secure_installation
y
0
y
y
n
y
systemctl status mysql.service
sudo mysql -u root -p
123456

mysql 远程访问

为了开启MySQL的远程连接,你需要进行几个步骤来确保服务器配置正确,并且安全措施得当。以下是开启MySQL远程连接的基本步骤:

1. 确认MySQL服务运行状态

首先,确保MySQL服务正在运行。你可以在服务器上使用如下命令来检查MySQL服务状态:

sudo systemctl status mysql

或者使用老的系统V命令:

sudo service mysql status

2. 修改MySQL配置文件

编辑MySQL的配置文件(一般位于/etc/mysql/mysql.conf.d/mysqld.cnf/etc/my.cnf),修改bind-address参数。默认情况下,这个参数设置为127.0.0.1(只允许本地连接):

bind-address = 0.0.0.0

设置为0.0.0.0表示接受所有IPv4地址的连接。如果你想要更加精确地控制,可以设置为特定的IP地址。

3. 重启MySQL服务

修改配置后,需要重启MySQL服务使改动生效:

sudo systemctl restart mysql

或者使用老的命令:

sudo service mysql restart

4. 创建允许远程连接的用户

你需要创建一个用户并授权这个用户从远程访问数据库。可以使用MySQL命令行工具来完成:

CREATE USER 'username'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;

这里'username'@'%'中的%表示允许从任何IP地址连接。如果你想限制只能从特定IP地址连接,可以将%替换为具体的IP地址。

查看系统用户

select * from mysql.user \G;

5. 配置防火墙(如果有的话)

如果服务器运行了防火墙,你需要开放MySQL的默认端口(通常是3306)以允许外部访问:

sudo ufw allow 3306

或者,如果使用的是iptables:

sudo iptables -A INPUT -p tcp --dport 3306 -j ACCEPT

6. 测试远程连接

使用MySQL客户端软件或命令行工具测试远程连接是否成功:

mysql -h server_ip -u username -p

这里server_ip是MySQL服务器的IP地址。

确保在进行这些操作时考虑到安全性,尤其是在生产环境中。避免使用root用户远程访问,限制可访问IP,并使用强密码。这些步骤应该帮助你成功设置MySQL的远程连接。

本地安装 navicat

.net ef core 连接 mysql

  • 安装postman

要在.NET Core Web API项目中使用Entity Framework Core (EF Core) 连接到MySQL数据库,你需要进行几个步骤来设置和配置。以下是详细的步骤说明:

1. 安装必要的NuGet包

首先,你需要在你的项目中安装EF Core和MySQL的数据提供程序包。对于MySQL,推荐使用Pomelo.EntityFrameworkCore.MySql,它是一个流行的、社区驱动的MySQL连接库,支持.NET Core。在你的项目目录中打开终端或命令提示符,运行以下命令:

dotnet add package Pomelo.EntityFrameworkCore.MySql
dotnet add package Microsoft.EntityFrameworkCore

2. 配置数据库上下文

创建一个继承自DbContext的类,这个类将代表你的数据库上下文。例如:

using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

    // DbSets go here
    public DbSet<YourEntity> YourEntities { get; set; }

    // Configure Fluent API settings here
}

3. 在Startup.cs中配置服务

Startup.cs文件中的ConfigureServices方法中,添加EF Core服务并配置连接字符串来连接到你的MySQL数据库:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    // Add EF Core
    services.AddDbContext<MyDbContext>(options =>
        options.UseMySql("server=localhost;database=mydatabase;user=myuser;password=mypassword",
            new MySqlServerVersion(new Version(8, 0, 21)))); // Make sure to adjust the version number
}

确保替换server, database, user, 和password为你的MySQL服务器的实际参数。

4. 使用数据库迁移

如果你的数据库是新的或者你需要在数据库上应用代码首次更改,你应该使用EF Core迁移。首先,添加迁移工具的NuGet包:

dotnet add package Microsoft.EntityFrameworkCore.Design

然后,运行以下命令创建一个新的迁移:

dotnet ef migrations add InitialCreate

应用迁移到数据库:

dotnet ef database update

这将创建数据库(如果它还不存在的话)并应用你定义的模式。

5. 使用你的数据库上下文

现在,你可以在你的控制器或其他服务中注入MyDbContext并使用它来进行数据库操作。

public class YourController : ControllerBase
{
    private readonly MyDbContext _context;

    public YourController(MyDbContext context)
    {
        _context = context;
    }

    // Your API methods here
}

这些步骤为你的.NET Core Web API项目设置了使用EF Core连接MySQL数据库的基础。你可以开始定义你的模型、创建迁移,并通过你的API与数据库交互了。确保在部署到生产环境前仔细检查连接信息和安全设置。

18日

sqlsugerapi

感觉与efcore 差不多

jwt 身份验证

注意的是 IssuerSigningKey 需要一样

ValidIssuer,ValidAudience 可能需要一样

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);
    // 添加以下配置
    builder.WebHost.ConfigureKestrel(serverOptions =>
    {
        serverOptions.ListenAnyIP(8461); // 监听所有IP地址的8461端口
    });


    // 添加JWT认证
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "yourIssuer",
                ValidAudience = "yourAudience",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yourLongerSecretKey123123123123123123123123123123123123123123"))
            };
        });


    // 添加SqlSugar服务
    builder.Services.AddScoped<ISqlSugarClient>(provider =>
    {
        return new SqlSugarClient(new ConnectionConfig()
        {
            ConnectionString = "server=localhost;database=test;user=root;password=123456", // 替换为你的数据库连接字符串
            DbType = DbType.MySql, // 使用的数据库类型
            IsAutoCloseConnection = true,
        });
    });



    builder.Services.AddControllers();


    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    //builder.Services.AddSwaggerGen();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        //app.UseSwagger();
        //app.UseSwaggerUI();
    }
    app.UseAuthentication();
    app.UseAuthorization();



    app.MapControllers();


    //using (var scope = app.Services.CreateScope())
    //{
    //    var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
    //    db.CodeFirst.InitTables(typeof(WebApplication1.DbModel.User));
    //}

    app.Run();
}



[ApiController]
[Route("api")]
public class AuthController : ControllerBase
{
    private readonly ISqlSugarClient dbContext;

    public AuthController(ISqlSugarClient dbContext)
    {
        this.dbContext = dbContext;
    }

    [HttpPost("login")]
    public IActionResult Login([FromBody] LoginModel login)
    {
        // 这里进行用户验证逻辑
        if (login.Username == "test" && login.Password == "password")
        {
            var token = GenerateJwtToken(login.Username);
            return Ok(new { Token = token });
        }
        return Unauthorized();
    }

    public string GenerateJwtToken(string username)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yourLongerSecretKey123123123123123123123123123123123123123123"));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };
        var token = new JwtSecurityToken(
            issuer: "yourIssuer",
            audience: "yourAudience",
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: credentials);
        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}