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

相关推荐
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
HH牛码2 小时前
C#学生管理系统 进阶(通过接口,继承接口的类,实现接口约束_对List中存储的数据进行排列)
c#
吾与谁归in3 小时前
C#实现本地Deepseek模型及其他模型的对话
人工智能·c#·wpf·deepseek
子蛟7 小时前
Get a free SSL certificate interface.
c#·ssl
一只蜗牛儿11 小时前
C# 版 OpenCV:OpenCVSharp 最详细最全面教程(万字详细总结)
开发语言·opencv·c#
学海无涯,行者无疆11 小时前
使用Jenkins实现Windows服务器下C#应用程序发布
windows·c#·jenkins·.net·cicd·自动发布·一键发布
tnnnnt13 小时前
今天锐评一下C#
开发语言·c#
Sator115 小时前
C#与AI的交互(以DeepSeek为例)
ai·语言模型·c#
玩c#的小杜同学16 小时前
从“Switch-case“到“智能模式“:C#模式匹配的终极进化指南
开发语言·前端·c#·.net
Rverdoser17 小时前
在 Centos7 上部署 ASP.NET 8.0 + YOLOv11 的踩坑实录
后端·yolo·asp.net