How to use `Masa MiniApi` in existing projects?

First of all, we have created an empty WebApiproject template. This project template MasaFrameworkhas nothing to do with itself. We only use the package MasaFrameworkfor this blog.MiniApi

  1. Created Asp.NET Core 空project template

  1. project nameMFMiniApi

  1. For other information, see the picture, cancel Httpsthe configuration, or choose,

  1. This is an empty project template

  2. InstallMasa MiniApi

    Search Masa.Contrib.Service.MinimalAPIs, please pay attention to the selection 包括发行版, because 1.0the version has not been released, so use the preview version first

  1. install itSwagger

    search Swashbuckle.AspNetCoreinstall

  2. useMasaMiniApi

    modify Program.csthe code

    using Microsoft.OpenApi.Models;
    
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddEndpointsApiExplorer();
    
    builder.Services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
    
    var app = builder.AddServices();
    
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });
    
    await app.RunAsync();
    
    

    Create Servicefolder and then createDemoService.cs

    Internal code:

    namespace MFMiniApi.Service;
    
    public class DemoService : ServiceBase
    {
        public string PostAsync()
        {
            return "成功了吗";
        }
    }
    
    
  3. Start the project by MiniApiimplementing a registry Apiservice

MasaMiniApiFunction:

Minimal APIsIt is very lightweight, and the writing method is very simple, but because of this, it also brings us some coding problems. Let's take a look at the difference between the original Minimal APIswriting method and Masathe provided one.Minimal APIs

native writing

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/api/v1/users/{id}", (Guid id)=>
{
    // todo: 查询用户信息
    var user = new User()
    {
        Id = id,
        Name = "Tony"
    };
    return Task.FromResult(Results.Ok(user));
});

app.MapPost("/api/v1/users", ([FromBody] UserRequest request)=>
{
    //todo: 添加用户逻辑
    return Task.FromResult(Results.Accepted());
});

app.MapDelete("/api/v1/users/{id}",(Guid id)=>
{
    //todo: 删除用户逻辑
    return Task.FromResult(Results.Accepted());
});

app.MapPut("/api/v1/users/{id}",(Guid id, [FromBody] EditUserRequest request)=>
{
    //todo: 修改用户逻辑
    return Task.FromResult(Results.Accepted());
});

app.Run();

MasaMiniApi

create UserService.cs, use case自动注册

using Microsoft.AspNetCore.Mvc;

namespace MFMiniApi.Service;

public class UserService : ServiceBase
{
    /// <summary>
    /// Get: /api/v1/users/{id}
    /// </summary>
    public Task<IResult> GetAsync(Guid id)
    {
        // todo: 查询用户信息
        var user = new User()
        {
            Id = id,
            Name = "Tony"
        };
        return Task.FromResult(Results.Ok(user));
    }

    /// <summary>
    /// Post: /api/v1/users
    /// </summary>
    public Task<IResult> AddAsync([FromBody] UserRequest request)
    {
        //todo: 添加用户逻辑
        return Task.FromResult(Results.Accepted());
    }

    /// <summary>
    /// Delete: /api/v1/users/{id}
    /// </summary>
    public Task<IResult> DeleteAsync(Guid id)
    {
        //todo: 删除用户逻辑
        return Task.FromResult(Results.Accepted());
    }

    /// <summary>
    /// Put: /api/v1/users/{id}
    /// </summary>
    public Task<IResult> UpdateAsync(Guid id, [FromBody] EditUserRequest request)
    {
        //todo: 修改用户逻辑
        return Task.FromResult(Results.Accepted());
    }
}

UserService.cs,Use Cases手动注册

public class UserService : ServiceBase
{
    public UserService()
    {
        RouteOptions.DisableAutoMapRoute = true;//当前服务禁用自动注册路由

        App.MapGet("/api/v1/users/{id}", GetAsync);
        App.MapPost("/api/v1/users", AddAsync);
        App.MapDelete("/api/v1/users/{id}", DeleteAsync);
        App.MapPut("/api/v1/users/{id}", UpdateAsync);
    }

    public Task<IResult> GetAsync(Guid id)
    {
        // todo: 查询用户信息
        var user = new User()
        {
            Id = id,
            Name = "Tony"
        };
        return Task.FromResult(Results.Ok(user));
    }

    public Task<IResult> AddAsync([FromBody] UserRequest request)
    {
        //todo: 添加用户逻辑
        return Task.FromResult(Results.Accepted());
    }

    public Task<IResult> DeleteAsync(Guid id)
    {
        //todo: 删除用户逻辑
        return Task.FromResult(Results.Accepted());
    }

    public Task<IResult> UpdateAsync(Guid id, [FromBody] EditUserRequest request)
    {
        //todo: 修改用户逻辑
        return Task.FromResult(Results.Accepted());
    }
}

MasaMiniApiglobal configuration for

parameter name Parameter Description Defaults
DisableAutoMapRoute Disable automap routing false
Prefix prefix api
Version Version v1
AutoAppendId Does the route contain {Id}, for example: /api/v1/user/ true
PluralizeServiceName Whether to enable pluralization of the service name true
GetPrefixes Used to identify the current method type as Geta request new List<string> { "Get", "Select", "Find" }
PostPrefixes Used to identify the current method type as Posta request new List<string> { "Post", "Add", "Upsert", "Create", "Insert" }
PutPrefixes Used to identify the current method type as Puta request new List<string> { "Put", "Update", "Modify" }
DeletePrefixes Used to identify the current method type as Deletea request new List<string> { "Delete", "Remove" }
DisableTrimMethodPrefix Disable remove method prefixes (above Get, Post, Put, Deleterequested prefixes) false
MapHttpMethodsForUnmatched After failing to match the request method through the method name prefix, the route will use the specified HttpMethod to initiate the request Support Post, Get, Delete, Putthis method is not supported by Swagger, and the API cannot be displayed normally
Assemblies The assembly used to scan the service MasaApp.GetAssemblies()(Global Assembly collection, the default is the current domain assembly collection)
RouteHandlerBuilder Based RouteHandlerBuilderon delegation, it can be used for authority authentication, CORS , etc. null

In-service configuration

parameter name Parameter Description Default value (not assigned to null)
BaseUri root address
ServiceName service name
RouteHandlerBuilder Delegation based on RouteHandlerBuilder, which can be used for authority authentication, CORS , etc.
RouteOptions (object) local routing configuration
DisableAutoMapRoute Disable automap routing
Prefix prefix
Version Version
AutoAppendId Whether to include {Id}font> in the route, for example: /api/v1/user/{id}
PluralizeServiceName Whether to enable pluralization of the service name
GetPrefixes Used to identify the current method type as Geta request
PostPrefixes Used to identify the current method type as Posta request
PutPrefixes Used to identify the current method type as Puta request
DeletePrefixes Used to identify the current method type as Deletea request
DisableTrimMethodPrefix Disable remove method prefixes (above Get, Post, Put, Deleterequested prefixes)
MapHttpMethodsForUnmatched After failing to match the request method through the method name prefix, the route will use the specified HttpMethod to initiate a request. This method is not supported by Swagger, and the API cannot be displayed normally.

MiniApi Documentation

MASA Framework (masastack.com)

这是官方文档地址,MasaFramework提供了很多的包都没有存在什么强依赖,都可以单独拿到项目中使用,这也是我目前一直学习Masaframework的原因,

好了MasaMiniApi的使用案例介绍到这里

来自token的分享

技术交流群:737776595

Guess you like

Origin blog.csdn.net/xiaohucxy/article/details/130233530