FastApi 1.0.36

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.36
NuGet\Install-Package FastApi -Version 1.0.36
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.36" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add FastApi --version 1.0.36
#r "nuget: FastApi, 1.0.36"
#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.36

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

FastApi

介绍

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

软件架构

软件架构说明

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

var fastApp = new FastApp(app)
{
	LogTime = true
};

//过滤器
fastApp.AddFilter(new FastFilter
{
	ExecuteAsync = async ctx =>
	{
		//string token = ctx.HttpContext.Request.Headers["token"];
		//if (string.IsNullOrEmpty(token))
		//{
		//    await ctx.HttpContext.Response.WriteAsJsonAsync(new { msg = "授权失败" });
		//    return false;
		//}
		ctx.UserData.Add("user", new LoginUser() { Name = "李四" });
		ctx.UserData.Add("aa", "用户自定义数据");

		return true;
	}
});

//自定义参数
fastApp.AddParams(typeof(LoginUser), new FastParamCreator
{
	Create = ctx =>
	{
		return ctx.UserData["user"];
	}
});

//自定义参数,依赖注入
fastApp.AddParams(typeof(ILifetimeScope), new FastParamCreator
{
	Create = ctx =>
	{
		return AutofacHelper.GetScope();
	},
	DisposeAsync = async (ctx, obj) =>
	{
		var scope = (ILifetimeScope)obj;
		await scope.DisposeAsync();
	}
});

//自定义参数事务
fastApp.AddParams(typeof(DistributedTransaction), new FastParamCreator
{
	Create = ctx =>
	{
		var tran = new DistributedTransaction();
		tran.ShowResult = true;
		return tran;
	},
	//DisposeAsync = async (ctx, obj) =>
	//{
	//    var tran = (DistributedTransaction)obj;
	//    await tran.DisposeAsync();
	//},
	CommitAsync = async (ctx, obj) =>
	{
		var tran = (DistributedTransaction)obj;
		await tran.CommitAsync();
	},
	RollbackAsync = async (ctx, obj) =>
	{
		var tran = (DistributedTransaction)obj;
		await tran.RollbackAsync();
		var val = string.Join(',', tran.Result.Values);
		if (!string.IsNullOrEmpty(val))
		{
			throw new Exception($"事务错误{val} ");
		}
	}
});            

fastApp.AddRoute("home", typeof(HomeModule));
fastApp.AddRoute("test", typeof(TestModule)); //注册类
fastApp.AddRoute(typeof(StudentModule).Assembly); //注册程序集

fastApp.OnBeforeResponseAsync += async (fastCtx) =>
{
	var result = new { code = 0, data = fastCtx.ResponseData };
	await fastCtx.HttpContext.Response.WriteAsJsonAsync(result, fastApp.JsonOptions);
};

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.OnExceptionAsync += async (fastCtx, ex) =>
{
	Console.WriteLine($"方法执行时间:{fastCtx.ExecuteTime}ms,序列化执行时间:{fastCtx.JsonSerialTime}ms");
	//Console.WriteLine($"FastApp发生异常:{ex.Message}\n" + ex.StackTrace);
	var result = new { code = -1, msg = ex.Message };
	await fastCtx.HttpContext.Response.WriteAsJsonAsync(result);
};

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

[FastRoute("student")]
public class StudentModule
{
	
	DistributedTransaction _tran;
	//构造函数
	public StudentModule(DistributedTransaction tran)
	{
		_tran = tran;
	}

	public string index(ILifetimeScope scope)
	{
		return "student index";
	}
	
	//static method 静态方法
	public static string index2()
	{
		return "this is static method";
	}

	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]
	public string Add2([FastForm] string a)
	{
		return "你好2" + a;
	}
}
//swagger

<ItemGroup Condition="'$(Configuration)'=='Debug'">
	<PackageReference Include="FastApi.Swag" Version="1.0.23" />
</ItemGroup>

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var fastApp = new FastApp(app)
{
    LogTime = true
};

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.OnResponse += (baseSchema) =>
            //{
            //    var schema = new NJsonSchema.JsonSchema();
            //    schema.Type = NJsonSchema.JsonObjectType.Object;
            //    schema.Properties.Add("code", new NJsonSchema.JsonSchemaProperty { Type = NJsonSchema.JsonObjectType.Integer });
            //    schema.Properties.Add("msg", new NJsonSchema.JsonSchemaProperty { Type = NJsonSchema.JsonObjectType.String });
            //    var dataPro = new NJsonSchema.JsonSchemaProperty();
            //    if (baseSchema.Example != null)
            //    {
            //        dataPro.ActualSchema.Example = baseSchema.Example;
            //    }
            //    else
            //    {
            //        //dataPro.AdditionalPropertiesSchema = baseSchema.ActualSchema;
            //    }
            //    schema.Properties.Add("data", dataPro);
            //    return schema;
            //};

            fastSwag.CreateApiJsonFile($@"{Environment.CurrentDirectory}\wwwroot\swagger");

            Console.WriteLine("Swagger文档生成成功!");
#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;
	}
}

//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 was computed.  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.49 0 5/20/2024