Skip to content

high performance and lightweight web api and websocket server components,performance higher than asp.net core mvc api 200%, support dotnet core and standard 2.0

License

Notifications You must be signed in to change notification settings

top5five/FastHttpApi

Repository files navigation

BeetleX.FastHttpApi is a lightweight and high-performance HTTP service component in the dotnet core platform that supports WebSocket and SSL.

samples

[https://github.com/beetlex-io/BeetleX-Samples]

Web Framework Benchmarks

Round 20benchmarks-round20

Using

Install BeetleX.FastHttpApi

Install-Package BeetleX.FastHttpApi

Base sample code

[Controller]classProgram{privatestaticBeetleX.FastHttpApi.HttpApiServermApiServer;staticvoidMain(string[]args){mApiServer=newBeetleX.FastHttpApi.HttpApiServer();mApiServer.Options.LogLevel=BeetleX.EventArgs.LogType.Trace;mApiServer.Options.LogToConsole=true;mApiServer.Debug();//set view path with vs project foldermApiServer.Register(typeof(Program).Assembly);//mApiServer.Options.Port=80; set listen port to 80mApiServer.Open();//default listen port 9090 Console.Write(mApiServer.BaseServer);Console.Read();}// Get /hello?name=henry // or// Get /hello/henry[Get(Route="{name}")]publicobjectHello(stringname){return$"hello {name}{DateTime.Now}";}// Get /GetTime publicobjectGetTime(){returnDateTime.Now;}}

Url Map

mApiServer.Map("/",(ctx)=>{ctx.Result(newTextResult("map /"));});mApiServer.Map("/user/{id}",async(ctx)=>{ctx.Result(newTextResult((string)ctx.Data["id"]));});

Url rewrite

mApiServer.UrlRewrite.Add("/api/PostStream/{code}/{datacode}","/api/PostStream");mApiServer.UrlRewrite.Add("/api/PostStream/{code}","/api/PostStream");mApiServer.UrlRewrite.Add(null,"/gettime","/time",null);

Action route

[RouteMap("/map/{code}")][RouteMap("/map/{code}/{customer}")]publicobjectMap(stringcode,stringcustomer){returnnew{code,customer};}

Hosting and DI services

Install-Package BeetleX.FastHttpApi.Hosting

publicclassProgram{staticvoidMain(string[]args){HttpServerhost=newHttpServer(80);host.UseTLS("test.pfx","123456");host.Setting((service,option)=>{service.AddTransient<UserInfo>();option.LogToConsole=true;option.LogLevel=BeetleX.EventArgs.LogType.Info;});host.Completed(server =>{});host.RegisterComponent<Program>();host.Run();}}[Controller]publicclassHome{publicHome(UserInfouser){mUser=user;}publicobjectHello(){returnmUser.Name;}privateUserInfomUser;}publicclassUserInfo{publicstringName{get;set;}="admin";}

Windows service

classProgram{privatestaticHttpServermServer;staticvoidMain(string[]args){mServer=newHttpServer(80);mServer.IsWindowsServices=true;mServer.Setting((service,option)=>{option.LogToConsole=true;option.WriteLog=true;option.LogLevel=BeetleX.EventArgs.LogType.Info;});mServer.RegisterComponent<Home>();mServer.Run();}}[Controller]publicclassHome{publicobjectHello(stringname){return$"hello {name}";}}

EntityFrameworkCore extensions

BeetleX.FastHttpApi.EFCore.Extension

classProgram{staticvoidMain(string[]args){HttpApiServerserver=newHttpApiServer();server.AddEFCoreDB<NorthwindEFCoreSqlite.NorthwindContext>();server.Options.Port=80;server.Options.LogToConsole=true;server.Options.LogLevel=EventArgs.LogType.Info;server.Options.SetDebug();server.Register(typeof(Program).Assembly);server.AddExts("woff");server.Open();Console.Read();}}[Controller]publicclassWebapi{publicDBObjectList<Customer>Customers(stringname,stringcountry,EFCoreDB<NorthwindContext>db){Select<Customer>select=newSelect<Customer>();if(!string.IsNullOrEmpty(name))select&= c =>c.CompanyName.StartsWith(name);if(!string.IsNullOrEmpty(country))select&= c =>c.Country==country;select.OrderBy(c =>c.CompanyName.ASC());return(db.DBContext,select);}[Transaction]publicvoidDeleteCustomer(stringcustomer,EFCoreDB<NorthwindContext>db){db.DBContext.Orders.Where(o =>o.CustomerID==customer).Delete();db.DBContext.Customers.Where(c =>c.CustomerID==customer).Delete();}publicDBValueList<string>CustomerCountry(EFCoreDB<NorthwindContext>db){SQLsql="select distinct country from customers";return(db.DBContext,sql);}}

Setting https

  • HttpConfig.json
 "SSL": true, "CertificateFile": "you.com.pfx", "CertificatePassword": "******", 
  • Code
mApiServer.ServerConfig.SSL=true;mApiServer.ServerConfig.CertificateFile="you.com.pfx";mApiServer.ServerConfig.CertificatePassword="******";

Defined result

  • Text result
publicclassTextResult:ResultBase{publicTextResult(stringtext){Text=text==null?"":text;}publicstringText{get;set;}publicoverrideboolHasBody=>true;publicoverridevoidWrite(PipeStreamstream,HttpResponseresponse){stream.Write(Text);}}

Download result

publicobjectDownloadImport(stringid){Dictionary<string,object>result=newDictionary<string,object>();returnnewDownLoadResult(Newtonsoft.Json.JsonConvert.SerializeObject(result),$"test.json");}
  • Use
publicobjectplaintext(){returnnewTextResult("Hello, World!");}

Cookies

publicobjectSetCookie(stringname,stringvalue,IHttpContextcontext){Console.WriteLine(context.Data);context.Response.SetCookie(name,value);return$"{DateTime.Now}{name}={value}";}publicstringGetCookie(stringname,IHttpContextcontext){Console.WriteLine(context.Data);return$"{DateTime.Now}{name}= {context.Request.Cookies[name]}";}

Header

publicvoidSetHeader(stringtoken,IHttpContextcontext){context.Response.Header["Token"]=token;}publicstringGetHeader(stringname,IHttpContextcontext){returncontext.Request.Header[name];}

Data bind

  • Url

/hello?name=xxxor/hello/henry

[Get(Route="{name}")]publicobjectHello(stringname,IHttpContextcontext){return$"hello {name}{DateTime.Now}";}

/SetValue?id=xxx&value=xxxxor/SetValue/xxx-xxx

[Get(Route="{id}-{value}")]publicobjectSetValue(stringid,stringvalue,IHttpContextcontext){return$"{id}={value}{DateTime.Now}";}
  • Json

{"name":"xxxx","value":"xxx"}

[Post][JsonDataConvert]publicobjectPost(stringname,stringvalue,IHttpContextcontext){Console.WriteLine(context.Data);return$"{name}={value}";}

or

[Post][JsonDataConvert]publicobjectPost(Propertybody,IHttpContextcontext){Console.WriteLine(context.Data);return$"{body.name}={body.value}";}
  • x-www-form-urlencoded

name=aaa&value=aaa

[Post][FormUrlDataConvert]publicobjectPostForm(stringname,stringvalue,IHttpContextcontext){Console.WriteLine(context.Data);return$"{name}={value}";}
  • multipart/form-data
[Post][MultiDataConvert]publicobjectUploadFile(stringremark,IHttpContextcontext){foreach(varfileincontext.Request.Files)using(System.IO.Streamstream=System.IO.File.Create(file.FileName)){file.Data.CopyTo(stream);}return$"{DateTime.Now}{remark}{string.Join(",",(fromfsincontext.Request.Filesselectfs.FileName).ToArray())}";}
  • Read stream
[Post][NoDataConvert]publicobjectPostStream(IHttpContextcontext){Console.WriteLine(context.Data);stringvalue=context.Request.Stream.ReadString(context.Request.Length);returnvalue;}

Filter

  • Defined filter
publicclassGlobalFilter:FilterAttribute{publicoverrideboolExecuting(ActionContextcontext){Console.WriteLine(DateTime.Now+" globalFilter execting...");returnbase.Executing(context);}publicoverridevoidExecuted(ActionContextcontext){base.Executed(context);Console.WriteLine(DateTime.Now+" globalFilter executed");}}
  • Use
[CustomFilter]publicstringHello(stringname){returnDateTime.Now+" hello "+name;}

or

[Controller][CustomFilter]publicclassControllerTest{}
  • Skip filter
[SkipFilter(typeof(GlobalFilter))]publicstringHello(stringname){returnDateTime.Now+" hello "+name;}

Parameters validation

publicboolRegister([StringRegion(Min=5)]stringname,[StringRegion(Min=5)]stringpwd,[DateRegion(Min="2019-1-1",Max="2019-2-1")]DateTimedateTime,[EmailFormater]stringemail,[IPFormater]stringipaddress,[NumberRegion(Min=18,Max=56)]intage,[DoubleRegion(Min=10)]doublememory){returntrue;}

Async action

[Get(Route="{name}")]publicTask<String>Hello(stringname){stringresult=$"hello {name}{DateTime.Now}";returnTask.FromResult(result);}publicasyncTask<String>Wait(){awaitTask.Delay(2000);return$"{DateTime.Now}";}

Cross domain

[Options(AllowOrigin="www.ikende.com")]publicstringGetTime(IHttpContextcontext){returnDateTime.Now.ToShortDateString();}

Websocket

  • Server
[Controller]classProgram{privatestaticBeetleX.FastHttpApi.HttpApiServermApiServer;staticvoidMain(string[]args){mApiServer=newBeetleX.FastHttpApi.HttpApiServer();mApiServer.Debug();mApiServer.Register(typeof(Program).Assembly);mApiServer.Open();Console.Write(mApiServer.BaseServer);Console.Read();}// Get /hello?name=henry // or// Get /hello/henry[Get(R"{name}")]publicobjectHello(stringname){return$"hello {name}{DateTime.Now}";}// Get /GetTime publicobjectGetTime(){returnDateTime.Now;}}
  • Hello

Request json

{url: '/Hello',params: {name: 'test'}}
  • GetTime

Request json

{url: '/GetTime',params: {}}

About

high performance and lightweight web api and websocket server components,performance higher than asp.net core mvc api 200%, support dotnet core and standard 2.0

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C#90.5%
  • HTML5.8%
  • JavaScript3.7%