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

相关推荐
清风与日月11 小时前
c# 集成激光雷达(以思岚A1为例)
开发语言·c#
无极小卒11 小时前
如何在三维空间中生成任意方向的矩形内部点位坐标
开发语言·算法·c#
the白勺13 小时前
RabbitMQ-基础-总结
开发语言·c#
专注VB编程开发20年14 小时前
C#VB.NET中实现可靠的文件监控(新建、删除、改名、内容修改等事件的准确捕获)
spring·c#·.net·文件监控
csdn_aspnet14 小时前
使用 .NET 8 构建 RESTful Web API
restful·webapi·.net8
yi碗汤园16 小时前
【一文了解】C#反射
开发语言·unity·c#
T.Ree.18 小时前
汇编_读写内存
开发语言·汇编·c#
czhc114007566319 小时前
C#1114 枚举
开发语言·c#
吴名氏.20 小时前
电子书《ASP.NET MVC企业级实战》
后端·asp.net·mvc·编程语言
曹牧20 小时前
C#中,GetValueOrDefault方法
c#