# fastapi
**Repository Path**: znyet/fastapi
## Basic Information
- **Project Name**: fastapi
- **Description**: .net core快速api,支持静态方法,自定义过滤器,注入属性等等
- **Primary Language**: C#
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 1
- **Created**: 2022-08-02
- **Last Updated**: 2025-06-30
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# FastApi
#### 介绍
.net core快速api,支持静态方法,自定义过滤器,自定义参数等等
#### 软件架构
软件架构说明
```
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
//创建FastApp
var fastApp = new FastApp(app);
#region 添加自定义参数
fastApp.AddParams(typeof(LoginUser), new FastParamCreator
{
Create = ctx =>
{
return ctx.UserData["user"];
}
});
fastApp.AddParams(typeof(ILifetimeScope), new FastParamCreator
{
Create = ctx =>
{
return AutofacHelper.GetScope();
},
DisposeValueAsync = (ctx, obj) =>
{
var scope = (ILifetimeScope)obj;
return scope.DisposeAsync();
}
});
fastApp.AddParams(typeof(DistributedTransaction), new FastParamCreator
{
Create = ctx =>
{
var tran = new DistributedTransaction();
return tran;
},
//DisposeAsync = async (ctx, obj) =>
//{
// var tran = (DistributedTransaction)obj;
// await tran.DisposeAsync();
//},
CommitAsync = (ctx, obj) =>
{
var tran = (DistributedTransaction)obj;
return tran.CommitAsync();
},
RollbackAsync = (ctx, obj) =>
{
var tran = (DistributedTransaction)obj;
return tran.RollbackAsync();
}
});
#endregion
//过滤器
fastApp.AddFilter(new FastFilter
{
ExecuteAsync = async fastCtx =>
{
string token = fastCtx.HttpContext.Request.Headers["token"];
if (string.IsNullOrEmpty(token))
{
fastCtx.Ex = new FastException("授权失败");
return;
}
fastCtx.UserData.Add("user", new LoginUser() { Name = "李四" });
fastCtx.UserData.Add("aa", "用户自定义数据");
}
});
//添加路由
fastApp.AddRoute("home", typeof(HomeModule));
fastApp.AddRoute("test", typeof(TestModule));
fastApp.AddRoute(typeof(StudentModule).Assembly);
//限流器
var rateLimit = new FastRateLimit();
//开始请求前
fastApp.OnRequest += (fastCtx) =>
{
//【全局限流器】最多10个并发
var ok = rateLimit.WaitOne(fastCtx, "key", 10);
//【FastRateLimitAttribute】特性限流器
if (ok && fastCtx.Action.RateLimitCount > 0)
{
rateLimit.WaitOne(fastCtx, fastCtx.Action.RateLimitKey, fastCtx.Action.RateLimitCount);
}
Console.WriteLine($"OnRequest===>{fastCtx.RouteData}");
};
//响应数据前(统一返回json格式)
fastApp.OnResponseAsync += (fastCtx) =>
{
var result = new { code = 0, data = fastCtx.ResponseData, msg = "", time = fastCtx.ExecuteTime };
return fastCtx.HttpContext.Response.WriteAsJsonAsync(result, fastApp.JsonOptions, fastCtx.Token);
};
//请求结束后
fastApp.OnAfterRequestAsync += async (fastCtx) =>
{
//【全局限流器】释放
var ok = rateLimit.Release(fastCtx, "key");
//【FastRateLimitAttribute】特性限流器释放
if (ok && fastCtx.Action.RateLimitCount > 0)
{
rateLimit.Release(fastCtx, fastCtx.Action.RateLimitKey);
}
Console.WriteLine($"OnAfterRequestAsync,{fastCtx.Route}==>方法执行时间:{fastCtx.ExecuteTime}ms,序列化执行时间:{fastCtx.SerialTime}ms");
Console.WriteLine($"QueryForm请求方法参数:{JsonSerializer.Serialize(fastCtx.FastHttp?.GetQueryAndForm(), fastCtx.JsonOptions)}");
Console.WriteLine($"HttpRequest请求参数:{JsonSerializer.Serialize(fastCtx.GetRequestData(), fastCtx.JsonOptions)}");
if (fastCtx.Ex != null) //发生异常
{
//如果可以响应,则响应错误信息
if (fastCtx.CanResponse)
{
try
{
var result = new { code = -1, data = null as string, msg = fastCtx.Ex.Message, time = fastCtx.ExecuteTime };
await fastCtx.HttpContext.Response.WriteAsJsonAsync(result, fastApp.JsonOptions);
}
catch { }
}
Console.WriteLine($"OnAfterRequestAsync,{fastCtx.Route}==>发生异常:{fastCtx.Ex.Message}" + fastCtx.Ex.StackTrace);
}
};
//响应视图
fastApp.OnViewAsync += async (fastCtx, view) =>
{
var template = Engine.LoadTemplate(AppDomain.CurrentDomain.BaseDirectory + view.ViewPath);
template.Set("Model", view.ViewData, view.ViewData.GetType());
var html = await template.RenderAsync();
await fastCtx.HttpContext.Response.WriteAsync(html);
};
Console.WriteLine("IsDevelopment==>" + fastApp.IsDevelopment);
Console.WriteLine("IsProduction==>" + fastApp.IsProduction);
Console.WriteLine(fastApp.BaseDirectory);
Console.WriteLine(fastApp.ContentRootPath);
Console.WriteLine(fastApp.WebRootPath);
```
```
[FastRoute("student")]
public class StudentModule
{
DistributedTransaction _tran;
//构造函数
public StudentModule(DistributedTransaction tran)
{
_tran = tran;
}
[FastGet]
public string index(ILifetimeScope scope)
{
return "student index";
}
//static method 静态方法
public static string index2()
{
return "this is static method";
}
[FastPost]
public string Add(IFastHttp http)
{
return http.GetQuery("name") + http.UserData["aa"];
}
[FastRedirect]
public string baidu()
{
return "https://www.baidu.com";
}
[FastCustomer]
public async Task Down(IFastHttp http)
{
await http.WriteFileAsync(new byte[] { 1, 23, 4, 4 }, "下载的文件.zip");
}
//原始输出
[FastCustomer]
public void Jd(IFastHttp http)
{
http.Redirect("https://www.jd.com");
}
//清除过滤器
[FastFilterClear]
[FastPost]
public string Add2([FastForm] string a)
{
return "你好2" + a;
}
[FastPost]
[FastUpload]
[FastDownload]
public async Task GetUpload3([FastForm] string name, IFastHttp http)
{
var file = http.GetFileLength(0);
await http.WriteFileAsync(new byte[] { 1, 23, 4, 4 }, "下载的文件.txt");
}
}
```
```
//swagger
net8.0
enable
enable
True
12
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var fastApp = new FastApp(app);
fastApp.AddRoute("home", typeof(HomeModule));
#if DEBUG
var fastSwag = new FastApi.Swag.FastSwag(fastApp.FastModuleDict);
fastSwag.AddApiKey("token");
//fastSwag.AddJwtBearer();
//fastSwag.AddLogin("/login/gettoken", "['data']"); //auto login
fastSwag.OnCreateDocument += (doc) =>
{
doc.Info.Title = "API接口信息";
doc.Info.Description = "这是对接口信息的描述11";
};
fastSwag.CreateApiJsonFile($@"{Environment.CurrentDirectory}\wwwroot");
Console.WriteLine("Swagger文档生成成功!");
//swagger-ui
//https://github.com/swagger-api/swagger-ui/archive/refs/tags/v4.19.1.zip
#endif
public class HomeModule
{
readonly DistributedTransaction tran;
ILifetimeScope scope0;
public HomeModule(DistributedTransaction tran, ILifetimeScope scope0)
{
this.tran = tran;
this.scope0 = scope0;
}
///
/// 添加接口
///
/// 名字
///
///
/// 这是对接口的描述111
/// 换行的描述2222
///
/// {code:0,data:{},msg:""}
[FastCustomer]
public static string Add(string a)
{
return "你好" + a;
}
///
/// 自定义body
///
///
///
/// {name:"里斯",sex:1}
/// {code:0,data:{},msg:""}
[FastFilterClear]
public string Add2([FastBody] string a)
{
return "你好2" + a;
}
///
/// 删除
///
///
///
///
///
/// id.string.true@这是个id
/// name.string.true@名字
/// sex.string.false@性别
///
///
/// addrss.string.true@地址
/// phone.string@手机
/// fileName.file.true@文件
///
[FastPost]
public async Task UploadFiles(int id)
{
throw new Exception("发生异常,删除失败了");
return "删除" + id;
}
}
///
/// 主页
///
///
/// api备注信息
///
/// 分组一
public class PeopleModule
{
[FastUpload]
[FastDownload]
public async Task UploadDown(IFastHttp _http)
{
var fileName = _http.GetFileName(0);
}
[FastPost]
[FastPostStream]
public async Task PostStream([FastQuery] int id, IFastHttp _http)
{
using var reader = new StreamReader(_http.GetRequestStream());
return await reader.ReadToEndAsync() + id;
}
[FastPost]
[FastJsonStream]
[FastPostStream]
public async IAsyncEnumerable PostStream2(IFastHttp _http)
{
using var reader = new StreamReader(_http.GetRequestStream());
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
Console.WriteLine(line);
yield return line;
}
}
}
```
```
### ClientSdk Project(创建SDK给第三方调用)
var sdk = new FastClientSdk("MyApiSdk");
sdk.OnMessage += Console.WriteLine;
//add nuget package
sdk.Packages.Add("Dapper.Sharding");
//fix namespace
sdk.UsingPrefix.Add("Test.Dto");
//ignore folder
sdk.AddIgnoreFolder(@"..\Test.Dto\bin");
sdk.AddIgnoreFolder(@"..\Test.Dto\obj");
//add class folder
sdk.AddClassFolder(@"..\Test.Dto");
//add class file
sdk.AddClassFile(@".\People.cs");
//create client sdk project
await sdk.CreateProjectAsync(@"C:\", fastApp.FastModuleDict);
//build project release dll.
await sdk.BuildProjectAsync();
//now you can copy dll to other project call api
```
```
### ClientSdk File
var sdk2 = new FastClientSdk("Test");
await sdk2.CreateSdkFileAsync(@".\", fastApp.FastModuleDict);
```