3 Star 2 Fork 0

黄凌霄 / FasterBuild

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

FasterBuild

介绍

FasterBuild,更快的构建,开箱即用的公司级.net6 WebApi程序框架
内置自定义依赖注入,Json配置文件映射,Cron定时任务,Log组件、JWT认证等多种开箱即用功能,开源项目,可供修改使用。

软件架构

net6

安装教程

1.  NuGet搜索FastBuilder.NET 安装最新版本
2.  Install-Package FastBuilder.NET -Version 1.0.1(替换成最新版本)

使用说明

- Program里输入以下代码

var builder = WebApplication.CreateBuilder(args);
builder.FastBuild((option, configuration) =>{});

InitOption属性及方法介绍

UseJsonSetting(json模型匹配)

- class类和json文件的匹配注入

- 目的:配置文件单独储存,单独使用,隔离性强,方便维护

相关特性: JsonFromAttributeValueFromAttribute

目的示例

option.UseJsonSetting(settingOption =>
{
    //需要注入的Setting文件存放的程序集名称 默认主程序集
    settingOption.AssemblyName = "";
    //模型类所在命名空间 默认xxxxx.Setting
    settingOption.SettingModelNamespace = "";
    //模型类对应的json文件存放文件夹名称(必须是根目录下)默认根目录下的SettingModel文件夹
    settingOption.SettingJsonFolderName = "";
});

UseInjection(自定义DI注入)

目的:解决每新增一个服务就需要去添加一行注入代码这种繁琐工作

提供多种注入方式

- InjectionNamespace(一个命名空间下的整体注入)
- InjectionType(Type注入)
- InjectionServiceAndImplementationType(IService和Service注入)
- InjectionServiceAndImplementationNamespace(IService的命名空间和Service的命名空间 整体匹配注入)
- [Injection(DIPattern.Singleton)](特性注入,详情请看特性栏目)

相关特性: InjectionIgnoreAttribute


option.UseInjection(option =>
{
    /*
      示例:Namespace下的IService和Service的注入方式 其余方法可以f12到里面去看,都有注释
      场景:
      Repository:UserRepository,RoleRepository
      IRepository:IUserRepository,IRoleRepository
      原生需要一个一个去注入,比较麻烦,该方法只需要传入命名空间和匹配规则,就可实现一次性注入
    */
    option.InjectionServiceAndImplementationNamespace(serviceNamespace: "Repository", iServiceNamespace: "IRepository", match: "I{Implementation}", dIPattern: DIPattern.Singleton, assemblyName: "");
});

UseGlobalRequestLog(访问日志配置)

注意*:访问日志存储路径在 /Logs/Request 文件夹中
option.UseGlobalRequestLog(log =>
{
    //在启用jwt配置以后 设置请求日志的唯一值,比如userid等,默认为null请求日志不会存唯一值
    log.RequestLogUniqueKey = (token) => { return token; };
});

UseIISRestart(IISRestart dispose后释放重启)

目的:为了解决iis回收导致程序中持续任务停止的问题,需搭配另外一套重启程序来实现 具体可以看iisOption中的注释

提供一个重启后的触发事件,实现IRestart,然后注入该类即可
option.UseIISRestart((iisOption) =>
{
    iisOption.ThisApplicationIpHost = "";

    iisOption.IISRestartTaskIpHost = "";
});

输入图片说明

UseTimeJob(使用定时任务)

详情TimeJob定时任务 一栏介绍

option.UseTimeJob((toption) =>
{
    //任务setting的文件地址,默认为Setting/TimedJobSetting.json
    toption.JobSettingPath = "";
});

功能介绍

Log模块

- 注入即可使用 存储在程序根目录下的Logs文件夹下面

- 异步存储 无需担心性能问题

- 提供三个基础方法 存储介质:log文件
public WxController(ILog log)
{
    
}

Swagger

- 注意*:需要生成对应xml文件

- 访问地址:根目录/swagger/index.html

TimeJob定时任务

- 使用Cron表达式

相关特性: ExecuteNowAttributeSkipWhileExecutingAttribute

[SkipWhileExecuting, ExecuteNow]
public class TestTimeJob : JobBase
{
    [Autowired]
    public ILog _logger;

    /// <summary>
    /// 执行方法
    /// </summary>
    /// <returns></returns>
    public override async Task Execute()
    {
        Console.WriteLine($"TestTimeJob {DateTime.Now}");
        _logger.Info($"TestTimeJob {DateTime.Now}");
    }

    /// <summary>
    /// 完成回调 (不需要可以不重写)
    /// </summary>
    /// <param name="result"></param>
    /// <returns></returns>
    public override async Task FinishCallBack(JobResultModel result)
    {
        Console.WriteLine($"TestTimeJob Execute Status:{result.Sutus}");
    }
}
- Setting文件夹中添加TimedJobSetting.json

{
  "TestTimeJob": "0/1 * * * * ?",
  ...
}

Jwt全局认证以及加解密

- appsetting.json中添加以下配置,即可开启全局Jwt认证

"Jwt": {
   //是否开启全局认证
   "OpenGlobalAuthentication": true,
   //必须填写 否则认为不开启Jwt
   "SecretKey": "FasterBuild",
   //默认:20分钟 1200秒
   "Lifetime": 1200,
   //默认:Unauthorized
   "ErrorMessage": "Unauthorized",
   //请求Header中的Token名字,默认:Authorization
   "HeaderName":"Authorization"
 }
- 开启后request请求的header中需要添加配置中的HeaderName字段,否则就会返回401

- 框架提供新的Authorization,通过Authorization验证的接口返回时会在respone的header中添加配置中的HeaderName字段,前端可以拿到该字段进行下次接口请求来保证Authorization不会过期

- 不需要验证token的接口需要在方法上添加[AllowAnonymous]特性
- 框架提供jwt加解密帮助类 IJwtHelper,注入使用即可

private ILog _log;
private IJwtHelper _jwtHelper;

public TestController(ILog log, IJwtHelper jwtHelper)
{
     _log = log;
     _jwtHelper = jwtHelper;
}

Autowired属性获取容器注入实例

- 可以通过[Autowired]特性进行获取容器注入实例

- 还可以自己手动获取容器注入实例,提供了object和IServiceProvider的拓展方法,引用FastBuild既可使用

- 注*:该属性注入不影响net原有的构造函数获取容器注入实例
object:filter.WithAutowired(context.HttpContext.RequestServices);

IServiceProvider:app.Services.GetServiceWithAutowired<IRestart>();

相关特性: AutowiredAttribute

Attribute

DefaultReturnAttribute

加到action或者controller上来实现不使用全局返回格式
[HttpGet("Wechat"), AllowAnonymous, DefaultReturn]
public string WxBinding([FromQuery] WeChatSignModel model)
{
    try
    {
        _logger.LogInfo($"WxBinding_QueryString:{Request.QueryString.Value}");
        if (_wxRepsitory.CheckWxBind(model))
        {
            _logger.LogInfo("WxBinding Success");
            return model.Echostr;
        }
        else
        {
            _logger.LogInfo("WxBinding failure");
            return "校验失败";
        }
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "WxBinding ERROR");
        throw;
    }
}

InjectionAttribute

使用特性注入
[Injection(DIPattern.Singleton)]
public class CommonHttpInvoke
{

}

InjectionIgnoreAttribute

注入忽略,跟注入相关的都可以加这个特性,例如jsonSetting,自定义Injection,加上以后就会自动忽略该类的注入

注意*:[InjectionIgnore]特性在IService和Service的注入方式中需添加到Service上才可实现过滤
[InjectionIgnore]
public class HolidayRepository
{
    
}

SkipWhileExecutingAttribute

TimeJob定时任务的特性,运行中是否跳过,不加则不跳过
[SkipWhileExecuting]
public class TestTimeJob : IJob
{
    private ILog _logger;
    public TestTimeJob(ILog logger)
    {
        _logger = logger;
    }

    public async Task Execute()
    {
        Console.WriteLine($"TestTimeJob {DateTime.Now}");
        _logger.LogInfo($"TestTimeJob {DateTime.Now}", "TestTimeJob");
        GC.Collect();
    }
}

ExecuteNowAttribute

TimeJob定时任务的特性,服务启动是否立刻执行
[SkipWhileExecuting]
[ExecuteNow]
public class TestTimeJob : IJob
{
    private ILog _logger;
    public TestTimeJob(ILog logger)
    {
        _logger = logger;
    }

    public async Task Execute()
    {
        Console.WriteLine($"TestTimeJob {DateTime.Now}");
        _logger.LogInfo($"TestTimeJob {DateTime.Now}", "TestTimeJob");
        GC.Collect();
    }
}

AutowiredAttribute

属性获取服务,仍可以使用构造函数获取服务
public class Testclass
{
    [Autowired]
    private ILog _logger;

    public async Task TestMethod()
    {
        Console.WriteLine($"TestMethod{DateTime.Now}");
        _logger.LogInfo($"TestMethod{DateTime.Now}", "Testclass");
    }
}

JsonFromAttribute

UseJsonSetting特性,用来指定Json数据来源,不加则找类名一致的Json文件,相对路径
[JsonFrom(Path = "appsettings.json")]
public class DomainSetting
{
    /// <summary>
    /// Api地址
    /// </summary>
    public string ApiDomain { get; set; }

    /// <summary>
    /// Web端地址
    /// </summary>
    public string WebDomain { get; set; }
}

ValueFromAttribute

UseJsonSetting特性,用来指定属性值的来源,不加则找Json文件中字段名一致的数据
[JsonFrom(Path = "appsettings.json")]
public class DomainSetting
{
    /// <summary>
    /// Api地址
    /// </summary>
	[ValueFrom(Property="Domain")]
    public string ApiDomain { get; set; }

    /// <summary>
    /// Web端地址
    /// </summary>
    public string WebDomain { get; set; }
}

Exception

OutPutException(450异常)

抛出给用户看的 不进行日志记录,返回值中的Code为450

UnauthorizedException(401异常)

认证失败 不进行日志记录,返回值中的Code为401

公共帮助类

ServiceContainer(静态获取注入类)

ServiceContainer.GetService<ILog>();
注意*:非Http请求中,获取Scope类型服务会当成Transient类型返回

ActionCustomAttributes(获取本次调用接口的所有Attributes,包含控制器上的)

注意*:该帮助类为Scoped注入,注入方式为Singleton的类中不能使用

输入图片说明

后续新的功能使用方法会更新到此README中,持续更新中……

MIT License Copyright (c) 2022 黄凌霄 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

FasterBuild,更快的构建,开箱即用的公司级.net6 WebApi程序框架 内置自定义依赖注入,Json配置文件映射,Cron定时任务,Log组件、JWT认证等多种开箱即用功能,开源项目,可供修改使用。 展开 收起
C#
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
C#
1
https://gitee.com/huang_ling_xiao/faster-build.git
git@gitee.com:huang_ling_xiao/faster-build.git
huang_ling_xiao
faster-build
FasterBuild
master

搜索帮助