• Stars
    star
    640
  • Rank 70,324 (Top 2 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created about 6 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

a lightweight and high-performance http/websocket service component in the dotnet core platform that supports TLS.

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 20 benchmarks-round20

Using

Install BeetleX.FastHttpApi

Install-Package BeetleX.FastHttpApi

Base sample code

    [Controller]
    class Program
    {
        private static BeetleX.FastHttpApi.HttpApiServer mApiServer;
        static void Main(string[] args)
        {
            mApiServer = new BeetleX.FastHttpApi.HttpApiServer();
            mApiServer.Options.LogLevel = BeetleX.EventArgs.LogType.Trace;
            mApiServer.Options.LogToConsole = true;
            mApiServer.Debug();//set view path with vs project folder
            mApiServer.Register(typeof(Program).Assembly);
            //mApiServer.Options.Port=80; set listen port to 80
            mApiServer.Open();//default listen port 9090  
            Console.Write(mApiServer.BaseServer);
            Console.Read();
        }
        // Get /hello?name=henry 
        // or
        // Get /hello/henry
        [Get(Route="{name}")]
        public object Hello(string name)
        {
            return $"hello {name} {DateTime.Now}";
        }
        // Get /GetTime  
        public object GetTime()
        {
            return DateTime.Now;
        }
    }

Url Map

mApiServer.Map("/", (ctx) =>
{
    ctx.Result(new TextResult("map /"));
});

mApiServer.Map("/user/{id}", async (ctx) =>
{
    ctx.Result(new TextResult((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}")]
public object Map(string code, string customer)
{
    return new { code, customer };
}

Hosting and DI services

Install-Package BeetleX.FastHttpApi.Hosting

    public class Program
    {
        static void Main(string[] args)
        {
            HttpServer host = new HttpServer(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]
    public class Home
    {
        public Home(UserInfo user)
        {
            mUser = user;
        }

        public object Hello()
        {
            return mUser.Name;
        }

        private UserInfo mUser;
    }

    public class UserInfo
    {
        public string Name { get; set; } = "admin";
    }

Windows service

class Program
{
    private static HttpServer mServer;

    static void Main(string[] args)
    {
        mServer = new HttpServer(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]
public class Home
{
    public object Hello(string name)
    {
        return $"hello {name}";
    }
}

EntityFrameworkCore extensions

BeetleX.FastHttpApi.EFCore.Extension

class Program
{
    static void Main(string[] args)
    {
        HttpApiServer server = new HttpApiServer();
        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]
public class Webapi
{
    public DBObjectList<Customer> Customers(string name, string country, EFCoreDB<NorthwindContext> db)
    {
        Select<Customer> select = new Select<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]
    public void DeleteCustomer(string customer, EFCoreDB<NorthwindContext> db)
    {
        db.DBContext.Orders.Where(o => o.CustomerID == customer).Delete();
        db.DBContext.Customers.Where(c => c.CustomerID == customer).Delete();
    }

    public DBValueList<string> CustomerCountry(EFCoreDB<NorthwindContext> db)
    {
        SQL sql = "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
    public class TextResult : ResultBase
    {
        public TextResult(string text)
        {
            Text = text == null ? "" : text;
        }
        public string Text { get; set; }
        public override bool HasBody => true;
        public override void Write(PipeStream stream, HttpResponse response)
        {
            stream.Write(Text);
        }
    }

Download result

        public object DownloadImport(string id)
        {
           
            Dictionary<string, object> result = new Dictionary<string, object>();
            return new DownLoadResult(Newtonsoft.Json.JsonConvert.SerializeObject(result), $"test.json");
        }
  • Use
        public object plaintext()
        {
            return new TextResult("Hello, World!");
        }

Cookies

        public object SetCookie(string name, string value, IHttpContext context)
        {
            Console.WriteLine(context.Data);
            context.Response.SetCookie(name, value);
            return $"{DateTime.Now}{name}={value}";
        }

        public string GetCookie(string name, IHttpContext context)
        {
            Console.WriteLine(context.Data);
            return $"{DateTime.Now} {name}= {context.Request.Cookies[name]}";
        }

Header

        public void SetHeader(string token,IHttpContext context)
        {
            context.Response.Header["Token"]=token;
        }

        public string GetHeader(string name, IHttpContext context)
        {
            return  context.Request.Header[name];
        }

Data bind

  • Url

/hello?name=xxxor/hello/henry

        [Get(Route = "{name}")]
        public object Hello(string name, IHttpContext context)
        {
            return $"hello {name} {DateTime.Now}";
        }

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

        [Get(Route = "{id}-{value}")]
        public object SetValue(string id, string value, IHttpContext context)
        {
            return $"{id}={value} {DateTime.Now}";
        }
  • Json

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

        [Post]
        [JsonDataConvert]
        public object Post(string name, string value, IHttpContext context)
        {
            Console.WriteLine(context.Data);
            return $"{name}={value}";
        }

or

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

name=aaa&value=aaa

        [Post]
        [FormUrlDataConvert]
        public object PostForm(string name, string value, IHttpContext context)
        {
            Console.WriteLine(context.Data);
            return $"{name}={value}";
        }
  • multipart/form-data
        [Post]
        [MultiDataConvert]
        public object UploadFile(string remark, IHttpContext context)
        {
            foreach (var file in context.Request.Files)
                using (System.IO.Stream stream = System.IO.File.Create(file.FileName))
                {
                    file.Data.CopyTo(stream);
                }
            return $"{DateTime.Now} {remark} {string.Join(",", (from fs in context.Request.Files select fs.FileName).ToArray())}";
        }
  • Read stream
        [Post]
        [NoDataConvert]
        public object PostStream(IHttpContext context)
        {
            Console.WriteLine(context.Data);
            string value = context.Request.Stream.ReadString(context.Request.Length);
            return value;
        }

Filter

  • Defined filter
    public class GlobalFilter : FilterAttribute
    {
        public override bool Executing(ActionContext context)
        {
            Console.WriteLine(DateTime.Now + " globalFilter execting...");
            return base.Executing(context);
        }
        public override void Executed(ActionContext context)
        {
            base.Executed(context);
            Console.WriteLine(DateTime.Now + " globalFilter executed");
        }
    }
  • Use
        [CustomFilter]
        public string Hello(string name)
        {
            return DateTime.Now + " hello " + name;
        }

or

    [Controller]
    [CustomFilter]
    public class ControllerTest
    {
    
    }
  • Skip filter
        [SkipFilter(typeof(GlobalFilter))]
        public string Hello(string name)
        {
            return DateTime.Now + " hello " + name;
        }

Parameters validation

public bool Register(
      [StringRegion(Min = 5)]string name,
      [StringRegion(Min = 5)]string pwd,
      [DateRegion(Min = "2019-1-1", Max = "2019-2-1")]DateTime dateTime,
      [EmailFormater]string email,
      [IPFormater]string ipaddress,
      [NumberRegion(Min = 18, Max = 56)]int age,
      [DoubleRegion(Min = 10)]double memory
                  )
        {
           return true;
        }

Async action

        [Get(Route = "{name}")]
        public Task<String> Hello(string name)
        {
            string result = $"hello {name} {DateTime.Now}";
            return Task.FromResult(result);
        }

        public async Task<String> Wait()
        {
            await Task.Delay(2000);
            return $"{DateTime.Now}";
        }

Cross domain

        [Options(AllowOrigin = "www.ikende.com")]
        public string GetTime(IHttpContext context)
        {
            return DateTime.Now.ToShortDateString();
        }

Websocket

  • Server
[Controller]
    class Program
    {
        private static BeetleX.FastHttpApi.HttpApiServer mApiServer;
        static void Main(string[] args)
        {
            mApiServer = new BeetleX.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}")]
        public object Hello(string name)
        {
            return $"hello {name} {DateTime.Now}";
        }
        // Get /GetTime  
        public object GetTime()
        {
            return DateTime.Now;
        }
    }
  • Hello

Request json

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

Request json

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

More Repositories

1

BeetleX

high performance dotnet core socket tcp communication components, support TLS, HTTP, HTTPS, WebSocket, RPC, Redis protocols, custom protocols and 1M connections problem solution
C#
1,098
star
2

Bumblebee

.net core fast http and websocket gateway components
C#
351
star
3

XBlog

Personal blog websites system built on Beetlex.FastHttpApi framework
JavaScript
204
star
4

Beetle.DT

分布式压力测试工具
C#
190
star
5

BeetleX.Redis

A high-performance async/non-blocking redis client components for dotnet core,default data formater json protobuf and messagepack,support ssl
C#
185
star
6

WebApiBenchmark

Web api management and performance testing tools
C#
161
star
7

TCPBenchmarks

tcp,websocket,webapi性能测试工具
117
star
8

BeetleX-Samples

BeetleX micro services framework (tcp webapi websocket and xrpc) samples
C#
102
star
9

SmartRoute

SmartRoute(服务即集群)
C#
84
star
10

XRPC

dotnet high performance remote interface and delegate invoke(RPC) communication components,support millions RPS remote interface method invokes
C#
80
star
11

Log4Grid

Distributed Application Log Management
C#
42
star
12

EventNext

EventNext is logic interface design actors components for .net core
C#
41
star
13

WebBenchmark

webapi 管理和性能测试工具
39
star
14

HttpClients

BeetleX http/websocket client support ssl
C#
31
star
15

ec

elastic communication component for mono and .net
C#
29
star
16

BNR

业务流水号规则生成器
C#
26
star
17

SimpleDoc

轻量化在线文档发布服务
CSS
24
star
18

KFilter

脏字过虑组件
C#
23
star
19

downloads

beetlex应用服务下载:网关,VueHost,性能测试工具和大数据分析服务
21
star
20

AdminUI

Beetlex+Vuejs+Bootstrap admin ui website
Vue
20
star
21

CacheDB

C#
18
star
22

NetBenchmark

tpc http and websocket performance benchmark testing components
C#
18
star
23

ClusterConfiguration

Beetlex Webapi cluster configuration
HTML
14
star
24

BeetleX.EFCore.Extension

BeetleX.EFCore.Extension
C#
14
star
25

dotnet-rpc-benchmark

rpc component benchmarks for dotnet
C#
14
star
26

CodeBenchmarkDoc

concurrent test components for netstandard 2.0
C#
11
star
27

WebFamily

Beetlex快速Web开发框架,内置vue,element,fontawesome
JavaScript
11
star
28

WebAPI4Grid

WebAPI集群负载组件
C#
8
star
29

ConcurrentTest

Concurrent Testing
C#
8
star
30

SmartRoute.DLocks

SmartRoute分布式锁
C#
8
star
31

RazorEngine

RazorEngine
C#
7
star
32

Configuration4Net

远程配置文件加载组件
C#
7
star
33

IKendeCLI

command line parse for .net
7
star
34

Peanut

c#数据访问组件
C#
6
star
35

Doc

Beetlex相关组件使用文档
6
star
36

vue-autoui

vue-autoui
JavaScript
6
star
37

beetlex-io

5
star
38

CS4Script

c#动态脚本编译加载组件
C#
3
star
39

SmartRoute.MRC

Message routing center
C#
3
star
40

BeetleXjs

beetlex webapi基于vue的快速开发扩展
Vue
2
star
41

mqtt

high performance .NET library for MQTT based communication
C#
2
star