FastApi 1.0.52

There is a newer version of this package available.
See the version list below for details.
The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package FastApi --version 1.0.52
NuGet\Install-Package FastApi -Version 1.0.52
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.52" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add FastApi --version 1.0.52
#r "nuget: FastApi, 1.0.52"
#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.52

// Install FastApi as a Cake Tool
#tool nuget:?package=FastApi&version=1.0.52

FastApi

介绍

.net core快速api,支持静态方法,自定义过滤器,自定义参数等等

软件架构

软件架构说明

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

//创建FastApp
var fastApp = new FastApp(app);

//限流器
var rateLimit = new FastRateLimit();

//过滤器
fastApp.AddFilter(new FastFilter
{
    ExecuteAsync = async fastCtx =>
    {
        string token = fastCtx.HttpContext.Request.Headers["token"];
        if (string.IsNullOrEmpty(token))
        {
            fastCtx.Ex = new Exception("授权失败");
            return;
        }

        fastCtx.UserData.Add("user", new LoginUser() { Name = "李四" });
        fastCtx.UserData.Add("aa", "用户自定义数据");
    }
});

//开始请求前
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.OnBeforeResponseAsync += (fastCtx) =>
{
    var result = new { code = 0, data = fastCtx.ResponseData, msg = "", time = fastCtx.ExecuteTime };
    return fastCtx.HttpContext.Response.WriteAsJsonAsync(result, fastApp.JsonOptions, fastCtx.Token);
};

//响应结束后
fastApp.OnAfterResponseAsync += async (fastCtx) =>
{
    //【全局限流器】释放
    var ok = rateLimit.Release(fastCtx, "key");

    //【FastRateLimitAttribute】特性限流器释放
    if (ok && fastCtx.Action.RateLimitCount > 0)
    {
        rateLimit.Release(fastCtx, fastCtx.Action.RateLimitKey);
    }

    Console.WriteLine($"OnAfterResponseAsync,{fastCtx.Route}==>方法执行时间:{fastCtx.ExecuteTime}ms,序列化执行时间:{fastCtx.JsonSerialTime}ms");

    if (fastCtx.Ex != null) //发生异常
    {
        //浏览器没有取消操作,响应错误信息
        if (!fastCtx.HttpContext.RequestAborted.IsCancellationRequested)
        {
            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($"OnAfterResponseAsync,{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);
};

//添加自定义参数
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();
    }
});

//添加路由
fastApp.AddRoute("home", typeof(HomeModule));
fastApp.AddRoute("test", typeof(TestModule));
fastApp.AddRoute(typeof(StudentModule).Assembly);

[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;
	}
}
//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.39" />
</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\swagger");

	Console.WriteLine("Swagger文档生成成功!");

	//please download swagger-ui and copy dist files to wwwroot/swagger folder
	//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>
	public async Task<string> Del(int id)
	{
		 throw new Exception("发生异常,删除失败了");
		 return "删除" + id;
	}
}

/// <summary>
/// 主页
/// </summary>
/// <remarks>
/// api备注信息
/// </remarks>
/// <swag-group>分组一</swag-group>
public class PeopleModule
{
    
}

//FastFlurl create RestHelper.cs file
FastFlurl.CreateClassFile($"{Environment.CurrentDirectory}/../TestRest", "TestRest", "RestHelper", fastApp.FastModuleDict, FastFlurlLevel.ObjectType);

//now you can use RestHelper.cs class file to request api
var client = new RestHelper("http://localhost:5212");
var a = await client.Home_Add<string>(new { a = "Lili" });
Console.WriteLine(a);

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.53 43 6/13/2024