首页 > 其他分享 >Clear Code for Minimal API

Clear Code for Minimal API

时间:2024-05-20 17:08:55浏览次数:11  
标签:MapMethods Code Clear API static MapGroup IEndpointBase public

我在写MinimalAPI的时候,发现不能最清晰的看到每个API,原因就是:WebAPI中不断增长逻辑处理过程

于是我在想如何简化API至一行,在一点一点想办法中,发现了简化DotNET Minimal API的方式。特此记录下来这个思路给需要帮助的人。我的灵感来源于 C# 11 功能 - 接口中的静态虚拟成员,通过静态虚拟成员清晰整个API。


这是我思路的最终结果:在 Program.cs 中我们能通过一行代码,清晰的看到代码情况。
而无需指定平常不是很关心的处理过程和请求方式。

app.MapGroup("Connect", o =>
{
    o.MapMethods<Authorize>("Authorize");
    o.MapMethods<Authorize.Callback>("Authorize/Callback");
    o.MapMethods<Token>("Token");
    o.MapMethods<UserInfo>("UserInfo").RequireAuthorization(new AuthorizeAttribute()
    {
        AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme
    });
    o.MapMethods<Endsession>("Endsession");
});
app.MapGroup("Account", o =>
{
    o.MapMethods<Login>("Login");
    o.MapMethods<Externallogin>("Externallogin");
    o.MapMethods<Externallogin.Callback>("Externallogin/Callback");
    o.MapMethods<ConfirmationLogin>("ConfirmationLogin");
    o.MapMethods<ForgotPassword>("ForgotPassword");
    o.MapMethods<ResetPassword>("ResetPassword");
});

结果结束。


我们只需要简单的三步就可以做到这个事情,并且可以不用反射和其他的复杂过程。
第一步,我们需要创建(附带静态抽象函数的接口)IEndpointBase。

public interface IEndpointBase
{
    public static abstract IEnumerable<string> HTTPMethods();
    public static abstract Delegate Handler();
}

第二步,需要实现IEndpointBase。

public class Login : IEndpointBase
{
    public record AccountLoginRequest
    {
        [JsonPropertyName("u"), Required]
        public string UserName { get; set; } = default!;

        [JsonPropertyName("p"), Required]
        public string Password { get; set; } = default!;

        [JsonPropertyName("r"), Required]
        public string ReturnUrl { get; set; } = default!;

        [FromQuery]
        public bool UseCookies { get; set; }
    }
    public static Delegate Handler()
    {
        var callback = async ([FromBody] AccountLoginRequest request, [FromServices] SignInManager signInManager) =>
        {
            // Todo: returnUrl validate is success

            var result = await signInManager.PasswordSignInAsync(request.UserName, request.Password, request.UseCookies, lockoutOnFailure: true);
            return Results.Text(result.ToString());
        };
        return callback;
    }

    public static IEnumerable<string> HTTPMethods() => [HttpMethods.Post];
}

第三步:处理静态IEndpointBase,此时我们已经完成了这件事情。

public static RouteHandlerBuilder MapMethods<T>(this IEndpointRouteBuilder app, [StringSyntax("Route")] string pattern) where T : IEndpointBase
{
    return app.MapMethods(pattern, T.HTTPMethods(), T.Handler());
}

单纯的使用扩展好的 MapMethods 已经足够清晰了。


但如果有对API进行分组的要求,还是使用原生的还是不会清晰,原因是:

  1. 要对 MapGroup 的值赋予变量名,比如说 var accountGroup = app.MapGroup("Account"),每个组都要想个名字。accountGroup

  2. 不能清楚自己的边界,比如说 写代码时,有可能出现插队的情况,本来 accountGroup下面都是属于它的端点,结果不小心插进来一个别的。

于是简单的对MapGroup进行了扩展,最终结果在本文最上面。

public static void MapGroup(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string prefix, Action<IEndpointRouteBuilder> action)
{
    var group = endpoints.MapGroup(prefix);
    action(group);
}

总结:通过这种方式,代码结构已经清晰多了。若是有议,可以在评论区联系我。

标签:MapMethods,Code,Clear,API,static,MapGroup,IEndpointBase,public
From: https://www.cnblogs.com/YataoFeng/p/18202396

相关文章

  • MySQL几种编码格式的区别(utf8、utf8mb4、utf8mb4_general_ci、utf8mb4_unicode_ci 、u
    https://cloud.tencent.com/developer/article/1872879存储字符集utf8和utf8mb4utf8是Mysql中的一种字符集,只支持最长三个字节的UTF-8字符,也就是Unicode中的基本多文本平面。要在Mysql中保存4字节长度的UTF-8字符,需要使用utf8mb4字符集,但只有5.5.3版本以后......
  • THUWC PKUWC APIO 游记
    MyBlogsTHUSC前情提要:THUWC\(200+10\)参与奖。Day-1坐高铁啦啦啦。身份证落在出租车上,费了很大劲才找回来,感觉很不牛。晚上饥荒启动。Day1进考场前疯狂背诵dwt的sublime编译教程,进考场默写对了/kx/kx。T1唐题,一眼秒了。T2唐题,一眼秒了。T3想了一下,发现状态......
  • 随机二次元图片API第二弹
    Tips:当你看到这个提示的时候,说明当前的文章是由原emlog博客系统搬迁至此的,文章发布时间已过于久远,编排和内容不一定完整,还请谅解`随机二次元图片API第二弹日期:2018-3-4阿珏折腾代码浏览:17990次评论:33条时隔差2天三个月,距首个随机二次元图片API发布已有许久时间......
  • Fluent API 配置实体和数据库之间的映射关系
    1.配置主键protectedoverridevoidOnModelCreating(ModelBuildermodelBuilder){modelBuilder.Entity<Blog>().HasKey(b=>b.BlogId);//配置Blog实体的主键为BlogId} 2.配置属性和列protectedoverridevoidOnModelCreating(ModelBuildermodelBu......
  • C++身份证二要素实名认证api、实名认证接口
    在数字化时代背景下,个人信息安全成为了社会关注的焦点。为进一步加强网络空间的安全管理,提升服务效率,身份证实名认证接口的出现为各行业提供了更为安全、高效的身份验证解决方案。随着互联网+政务服务、金融科技、电子商务等领域的快速发展,实名认证需求日益增长。翔云身......
  • apisix~集成服务发现注册中心
    摘要当业务量发生变化时,需要对上游服务进行扩缩容,或者因服务器硬件故障需要更换服务器。如果网关是通过配置来维护上游服务信息,在微服务架构模式下,其带来的维护成本可想而知。再者因不能及时更新这些信息,也会对业务带来一定的影响,还有人为误操作带来的影响也不可忽视,所以网关非常......
  • [LeetCode] 1863. Sum of All Subset XOR Totals
    TheXORtotalofanarrayisdefinedasthebitwiseXORofallitselements,or0ifthearrayisempty.Forexample,theXORtotalofthearray[2,5,6]is2XOR5XOR6=1.Givenanarraynums,returnthesumofallXORtotalsforeverysubsetofnums.......
  • Codeforces Round 945 (Div. 2) (A - E)
    A每一轮对总分的贡献都是\(2\),如果\(p_1+p_2+p_3\)为奇数则无解。\(p_1+p_2\lep_3\),最多\(p_1+p_2\)轮。\(p_1+p_2>p_3\),可以\(1,2\)轮流将\(3\)耗完,然后互相匹配,最多\(\dfrac{p_1+p_2+p_3}{2}\)。B如何判断一个\(k_0\)是否符合条件?处......
  • AtCoder abc354E
    原题链接ProblemStatementTakahashiandAokiareplayingagameusing\(N\)cards.Thefrontsideofthe\(i\)-thcardhas\(A_i\)writtenonit,andthebacksidehas\(B_i\)writtenonit.Initially,the\(N\)cardsarelaidoutonthetable.Wit......
  • 开源低代码框架 ReZero API 正式版本发布 ,界面操作直接生成API
    一、ReZero简介ReZero是一款.NET中间件:全网唯一界面操作就能生成API, 可以集成到任何.NET6+API项目,无破坏性,也可让非.NET用户使用exe文件免费开源:MIT最宽松协议,一直从事开源事业十年,一直坚持开源1.1纯ReZero开发适合.NetCore零基础用户,大大简化了.NetCore开发门......