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

相关推荐
bugcome_com13 小时前
零基础入门C#:一篇搞懂核心知识点
c#
程序员敲代码吗16 小时前
如何通过命令行启动COMSOL的参数化、批处理和集群扫描
java·c#·bash
缺点内向18 小时前
C#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
喵叔哟19 小时前
06-ASPNETCore-WebAPI开发
服务器·后端·c#
2501_9307077819 小时前
使用 C# .NET 从 PowerPoint 演示文稿中提取背景图片
c#·powerpoint·.net
初级代码游戏20 小时前
套路化编程 C# winform 自适应缩放布局
开发语言·c#·winform·自动布局·自动缩放
大空大地202621 小时前
流程控制语句--switch多分支语句使用、while循环语句的使用、do...while语句、for循环
c#
kylezhao20191 天前
C#序列化与反序列化详细讲解与应用
c#
JQLvopkk1 天前
C# 实践AI :Visual Studio + VSCode 组合方案
人工智能·c#·visual studio
故事不长丨1 天前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#