C# .Net6搭建灵活的RestApi服务器

1、准备

C# .Net6后支持顶级语句,更简单的RestApi服务支持,可以快速搭建一个极为简洁的Web系统。推荐使用Visual Studio 2022,安装"ASP.NET 和Web开发"组件。

2、创建工程

关键步骤如下:

包添加了"Newtonsoft.Json",方便序列化和反序化。

3、工程代码

cs 复制代码
using Newtonsoft.Json;
using System.Runtime.CompilerServices;
using System.Text;

int bodySize = 8192;
Encoder encoder = Encoding.UTF8.GetEncoder();

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// 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.UseHttpsRedirection();

app.MapGet("/{*myUrl}", (HttpRequest request,string myUrl) => {
    return HttpRequestParse(request, myUrl);
});
app.MapPost("/{*myUrl}", (HttpRequest request, string myUrl) => {
    return HttpRequestParse(request, myUrl);
});

string HttpRequestParse(HttpRequest request, string myUrl)
{
    string body = "";
    using (var reader = new StreamReader(request.Body))
    {
        Task<string> t = reader.ReadToEndAsync();
        t.Wait();
        body = t.Result;
    }
    string msg = $"{myUrl} {request.Method} {request.Scheme} {request.Path} {request.QueryString} {body}";
    Console.WriteLine(msg);
    return msg;
}

app.Run();

代码中添加了Post和Get的全路径注册,并给出了如何解析请求数据和body数据的方法。返回值msg方面,建议返回一个Json对象,包含String Msg和int Code两个属性,方便应用使用。

4、部署文件

编译之后,默认的启动端口是http://localhost:5000,可以通过修改appsettings.json配置文件实现其他绑定("Kestrel"部分为新增)。

cs 复制代码
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*",
    "Kestrel": {
        "Endpoints": {
            "Http": {
                "Url": "http://*:9000"
            }
        }
    }
}

也可以通过命令行指定,如:

dotnet AspNetCore.Pascal.dll --urls "http://localhost:7001;https://localhost:7011"

根据微软的官方说明,默认的 JsonConfigurationProvider 会按以下顺序加载配置:

  1. appsettings.json
  2. appsettings.{Environment}.json:例如,appsettings.Production.jsonappsettings.Development.json 文件。 文件的环境版本是根据 IHostingEnvironment.EnvironmentName 加载的。 有关详细信息,请参阅在 ASP.NET Core 中使用多个环境

appsettings.{Environment}.json 值替代 appsettings.json 中的键。 例如,默认情况下:

  • 在开发环境中,appsettings.Development.json 配置会覆盖在 appsettings.json 中找到的值。
  • 在生产环境中,appsettings.Production.json 配置会覆盖在 appsettings.json 中找到的值。 例如,在将应用部署到 Azure 时。

如果必须保证配置值,请参阅 GetValue。 前面的示例只读取字符串,不支持默认值。

使用默认配置时,会通过 reloadOnChange: true 启用 appsettings.jsonappsettings.{Environment}.json 文件。 应用启动后,对 appsettings.jsonappsettings.{Environment}.json 文件所做的更改将由 JSON 配置提供程序读取。

5、参考资料

ASP.NET Core 中的配置

centos下dotnet服务启停脚本_centos dotnet 停止-CSDN博客

ASP.NET Core设置URLs的几种方法

最小 API 概述 | Microsoft Learn

相关推荐
IT规划师30 分钟前
C#|.net core 基础 - 扩展数组添加删除性能最好的方法
c#·.netcore·数组
时光追逐者1 小时前
分享6个.NET开源的AI和LLM相关项目框架
人工智能·microsoft·ai·c#·.net·.netcore
friklogff2 小时前
【C#生态园】提升C#开发效率:深入了解自然语言处理库与工具
开发语言·c#·区块链
__water10 小时前
『功能项目』回调函数处理死亡【54】
c#·回调函数·unity引擎
__water10 小时前
『功能项目』眩晕图标显示【52】
c#·unity引擎·动画事件
__water11 小时前
『功能项目』第二职业法师的平A【57】
c#·unity引擎·魔法球伤害传递
Java资深爱好者12 小时前
VB.NET中如何利用ASP.NET进行Web开发
前端·asp.net·.net
__water13 小时前
『功能项目』战士的伤害型技能【45】
c#·unity引擎·战士职业伤害型技能
君莫愁。14 小时前
【Unity】检测鼠标点击位置是否有2D对象
unity·c#·游戏引擎
Lingbug15 小时前
.Net日志组件之NLog的使用和配置
后端·c#·.net·.netcore