Asp.Net Core 动态生成WebApi

在WebApi架构体系中,一般需要先编写应用服务实现,再通过编写Controller来实现应用服务的Web接口。Controller中的代码作用仅仅是调用Service的方法,将Service提升为Web接口,其实完全可以通过动态生成WebApi来减少编码工作。在.Net示例项目ABP中已经实现了动态生成WebApi的功能,Panda.DynamicWebApi项目将这部分代码进行了抽取和封装,我们可以通过引用Panda.DynamicWebApi项目来实现动态生成WebApi。

第一步,通过Nuget添加Panda.DynamicWebApi的项目引用

在VS2019的Nuget包管理器中,搜索并添加Panda.DynamicWebApi的项目引用。

第二步,给Service添加[DynamicWebApi]特性,并继承IDynamicWebApi接口

[DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v1")]
    public class UserAppService : IDynamicWebApi
    {
        public List<UserInfo> GetUserList()
        {
            var userList = new List<UserInfo>();
            userList.Add(new UserInfo()
            {
                UserId = 1,
                UserName = "张三",
                PhoneNum = "13344455566",
                Address = "北京"
            });
            userList.Add(new UserInfo()
            {
                UserId = 2,
                UserName = "李四",
                PhoneNum = "13322233344",
                Address = "天津"
            });
            userList.Add(new UserInfo()
            {
                UserId = 3,
                UserName = "王五",
                PhoneNum = "13355566677",
                Address = "上海"
            });
            return userList;
        }
    }

注意:

(1)DynamicWebApi默认的服务命名后缀是AppService,这个可以配置;
(2)使用DynamicWebApi,必须在服务类上添加特性[ApiExplorerSettings(GroupName = "v1")],指定GroupName才能让Swagger展示接口;
(3)DynamicWebApi有一套默认的请求方式命名规则,这个可以自行配置,也可配置为全部是POST方式
第三步,在Startup类中的ConfigureServices方法中,配置启用DynamicWebApi

// 自定义配置
            services.AddDynamicWebApi((options) =>
            {
                // 指定全局默认的 api 前缀
                options.DefaultApiPrefix = null;

                // 指定全局默认的去除控制器后缀
                options.RemoveControllerPostfixes = new List<string>() { "Service" };

                // 清空API结尾,不删除API结尾;若不清空 CreatUserAsync 将变为 CreateUser
                options.RemoveActionPostfixes.Clear();

                // 自定义 ActionName 处理函数;
                options.GetRestFulActionName = (actionName) => actionName;
            });

 

posted on 2023-03-31 11:24  静以修身俭以养德  阅读(338)  评论(0编辑  收藏  举报

导航