FastApi 1.0.65
dotnet add package FastApi --version 1.0.65
NuGet\Install-Package FastApi -Version 1.0.65
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="FastApi" Version="1.0.65" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add FastApi --version 1.0.65
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: FastApi, 1.0.65"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install FastApi as a Cake Addin #addin nuget:?package=FastApi&version=1.0.65 // Install FastApi as a Cake Tool #tool nuget:?package=FastApi&version=1.0.65
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
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
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile Condition="'$(Configuration)'=='Debug'">True</GenerateDocumentationFile>
<LangVersion>12</LangVersion>
</PropertyGroup>
<ItemGroup Condition="'$(Configuration)'=='Debug'">
<PackageReference Include="FastApi.Swag" Version="1.0.50" />
</ItemGroup>
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;
}
/// <summary>
/// 添加接口
/// </summary>
/// <param name="a">名字</param>
/// <returns></returns>
/// <remarks>
/// 这是对接口的描述111
/// 换行的描述2222
/// </remarks>
/// <swag-res>{code:0,data:{},msg:""}</swag-res>
[FastCustomer]
public static string Add(string a)
{
return "你好" + a;
}
/// <summary>
/// 自定义body
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
/// <swag-body>{name:"里斯",sex:1}</swag-body>
/// <swag-res>{code:0,data:{},msg:""}</swag-res>
[FastFilterClear]
public string Add2([FastBody] string a)
{
return "你好2" + a;
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
/// <swag-query>
/// id.string.true@这是个id
/// name.string.true@名字
/// sex.string.false@性别
/// </swag-query>
/// <swag-form>
/// addrss.string.true@地址
/// phone.string@手机
/// fileName.file.true@文件
/// </swag-form>
[FastPost]
public async Task<string> UploadFiles(int id)
{
throw new Exception("发生异常,删除失败了");
return "删除" + id;
}
}
/// <summary>
/// 主页
/// </summary>
/// <remarks>
/// api备注信息
/// </remarks>
/// <swag-group>分组一</swag-group>
public class PeopleModule
{
[FastUpload]
[FastDownload]
public async Task UploadDown(IFastHttp _http)
{
var fileName = _http.GetFileName(0);
}
[FastPost]
[FastPostStream]
public async Task<string> PostStream([FastQuery] int id, IFastHttp _http)
{
using var reader = new StreamReader(_http.GetRequestStream());
return await reader.ReadToEndAsync() + id;
}
[FastPost]
[FastJsonStream]
[FastPostStream]
public async IAsyncEnumerable<string> 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);
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net6.0
- FastApi.Attributes (>= 1.0.30)
- FastEmit (>= 1.0.9)
-
net7.0
- FastApi.Attributes (>= 1.0.30)
- FastEmit (>= 1.0.9)
-
net8.0
- FastApi.Attributes (>= 1.0.30)
- FastEmit (>= 1.0.9)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on FastApi:
Package | Downloads |
---|---|
FastApi.Swag
My package description. |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated |
---|---|---|
1.0.65 | 109 | 12/20/2024 |