MASAMinimalAPI:创建MinimalAPI项目

  • MASAMinimalAPI:创建MinimalAPI项目已关闭评论
  • 167 次浏览
  • A+
所属分类:.NET技术
摘要

将原有的换成提问:为什么我们只写了一个app.MapGet,却生成了三个接口MASA MinimalAPI源码解析:为什么我们只写了一个app.MapGet,却生成了三个接口:https://note.raokun.top/archives/masaminimalapi-yuan-ma-jie-xi–wei-shen-me-wo-men-zhi-xie-le-yi-ge-appmapget-que-sheng-cheng-le-san-ge-jie-kou


项目准备

1.创建项目,选择webapi。取消勾选使用控制器。创建minimal Api项目

MASAMinimalAPI:创建MinimalAPI项目

2.创建成功后MinimalAPI的接口直接写在program.cs中

MASAMinimalAPI:创建MinimalAPI项目

3.引入nuget包:Masa.Contrib.Service.MinimalAPIs

MASAMinimalAPI:创建MinimalAPI项目

MinimalAPI改造

1. 在program.cs中加入以下内容

将原有的

var app = builder.Build(); 

换成

var app = builder.Services.AddServices(builder); 

2.自定义Service并继承ServiceBase

1.我们创建的一个自定义service如下:

    public class UserService : ServiceBase {         public UserService() : base() {             App.MapGet("/api/weatherforecast", GetWeatherForecast);         }         public async Task<WeatherForecast[]> PostWeather() {             return null;         }         public async Task< WeatherForecast[]> GetWeatherForecast() {             var summaries = new[]             {                 "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"             };             var forecast = Enumerable.Range(1, 5).Select(index =>         new WeatherForecast         (             DateOnly.FromDateTime(DateTime.Now.AddDays(index)),             Random.Shared.Next(-20, 55),             summaries[Random.Shared.Next(summaries.Length)]         ))         .ToArray();             return forecast;         }          public async Task<IResult> Register() {             return Results.Ok("注册成功");         }     }     public record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) {         public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);     } 

2.构建成功,查看swagger

MASAMinimalAPI:创建MinimalAPI项目MASAMinimalAPI:创建MinimalAPI项目

提问:为什么我们只写了一个app.MapGet,却生成了三个接口

MASA MinimalAPI源码解析:为什么我们只写了一个app.MapGet,却生成了三个接口:https://note.raokun.top/archives/masaminimalapi-yuan-ma-jie-xi--wei-shen-me-wo-men-zhi-xie-le-yi-ge-appmapget-que-sheng-cheng-le-san-ge-jie-kou

阅读如遇样式问题,请前往个人博客浏览: https://note.raokun.top
拥抱ChatGPT,国内访问网站:https://ai.firstsaofan.top
开源项目地址:https://github.com/firstsaofan/TerraMours