BeetleX.FastHttpApi Documentation

repository·master·Indexed 20 days ago

https://github.com/beetlex-io/fasthttpapi

A high-performance, lightweight HTTP service component for .NET Core supporting WebSockets, SSL, and advanced routing. It features attribute-based routing for servers, a proxy-based HttpApiClient for strongly-typed client actions, and system management endpoints via /__system for runtime configuration of server settings and rate limiting.

Tokens
7.6K
Snippets
21
Records
27
Agent score
71%

What's inside BeetleX.FastHttpApi

  1. Configure Hosting and Dependency Injection

    master

    For advanced hosting scenarios, install BeetleX.FastHttpApi.Hosting. This allows you to use an HttpServer instance, configure TLS, and register services into the DI container using the .Setting method.

    // Requires 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.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"; }
  2. Implement a basic HTTP API server

    master

    To create a high-performance HTTP API, instantiate BeetleX.FastHttpApi.HttpApiServer, register the assembly containing your controllers, and call Open(). You can define routes using attributes like [Get] on methods within your class. The server supports both query parameters (e.g., /hello?name=henry) and path parameters (e.g., /hello/henry) using the R"{name}" route template syntax.

    [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 /hello/henry
        [Get(R"{name}")]
        public object Hello(string name)
        {
            return $"hello {name} {DateTime.Now}";
        }
    
        // Get /GetTime
        public object GetTime()
        {
            return DateTime.Now;
        }
    }
  3. Install BeetleX.FastHttpApi

    master

    Install the core package via NuGet to use the high-performance HTTP service component in .NET Core.

    Install-Package BeetleX.FastHttpApi
  4. Create a basic HttpApiServer

    master

    To start a basic server, instantiate HttpApiServer, configure its options (like LogLevel and LogToConsole), register the assembly containing your controllers, and call Open(). By default, it listens on port 9090.

    [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.Open(); // default listen port 9090  
            Console.Write(mApiServer.BaseServer);
            Console.Read();
        }
    
        [Get(Route="{name}")]
        public object Hello(string name)
        {
            return $"hello {name} {DateTime.Now}";
        }
    }
  5. Use EntityFrameworkCore Extensions

    master

    The BeetleX.FastHttpApi.EFCore.Extension allows you to integrate EF Core directly into your controllers. You can inject EFCoreDB<TContext> into your methods to perform queries and transactions.

    // Requires BeetleX.FastHttpApi.EFCore.Extension
    class Program
    {
        static void Main(string[] args)
        {
            HttpApiServer server = new HttpApiServer();
            server.AddEFCoreDB<NorthwindEFCoreSqlite.NorthwindContext>();
            server.Register(typeof(Program).Assembly);
            server.Open();
        }
    }
    
    [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();
        }
    }
  6. Define client-side API actions using attributes

    master

    BeetleX.FastHttpApi allows you to define HTTP client actions by decorating methods in a class with specific attributes. The library uses reflection to map these methods to HTTP requests, handling routing, parameters, and data formatting automatically.

    Supported Attributes

    • [Controller(BaseUrl = "...")]: Applied to the class to define a common BaseUrl for all methods within the controller.
    • HTTP Verb Attributes:
      • [Get(Route = "...")]
      • [Post(Route = "...")]
      • [Put(Route = "...")]
      • [Del(Route = "...")]
    • Parameter Mapping Attributes:
      • [CHeader(Name = "...", Value = "...")]: Maps a parameter to an HTTP header. Can be applied to the class (for static headers) or the method.
      • [CQuery(Name = "...")]: Maps a parameter to an HTTP query string key.
      • [FormaterAttribute]: Defines how the request body should be formatted (applied to class or method).

    Parameter Resolution Logic

    When a method is called, parameters are resolved in the following priority:

    1. Header Parameters: If marked with [CHeader].
    2. Query String Parameters: If marked with [CQuery].
    3. Route Parameters: If the parameter name matches a placeholder in the Route template (e.g., /users/{id}).
    4. Data Parameters: All other parameters are treated as part of the request body (for POST/PUT) or query string (for GET/DELETE).
    [Controller(BaseUrl = "/api/v1")]
    [CHeader(Name = "Authorization", Value = "Bearer token")]
    public class MyApiClient
    {
        [Get(Route = "/users/{id}")]
        public async Task<User> GetUserAsync([CQuery(Name = "detail")] bool detail, string id)
        {
            // The library maps 'id' to the route, 'detail' to the query string,
            // and uses the BaseUrl + Route to form the final URL.
        }
    }
  7. Generate and use Access Tokens for system endpoints

    master

    System endpoints (except those explicitly marked with [SkipFilter(typeof(AccessTokenFilter))]) require an authorization token. The token follows a specific format used by the AccessTokenFilter to validate identity and expiration.

    Token Format: sign.timestamp_range

    1. sign: An HMAC-SHA1 signature of the encrypted timestamp range, using the server's AccessKey as the key.
    2. timestamp_range: A string in the format start_timestamp:end_timestamp (e.g., 1723000000:1723003600).

    Validation Logic:

    • The server extracts the AccessKey from its options.
    • It verifies the signature against the provided timestamp range.
    • It checks if the current server time falls between the start and end timestamps.

    Header Requirement: Pass the token in the request header defined by HeaderTypeFactory.AUTHORIZATION (typically Authorization).

  8. Use IHttpContext to manage HTTP and WebSocket requests

    master

    The IHttpContext interface is the primary way to interact with the current request/response lifecycle in BeetleX.FastHttpApi. It provides access to the HttpRequest, HttpResponse, ISession, and the underlying IDataContext.

    Depending on the connection type, the implementation behaves differently:

    • HTTP Context: Used for standard HTTP requests. Calling .Result(data) sends the data back as an HTTP response.
    • WebSocket Context: Used for WebSocket connections. Calling .Result(data) wraps the data in a DataFrame and sends it through the WebSocket session.

    Key capabilities include:

    • Session Access: Use the indexer context["name"] to get or set values in the ISession.
    • WebSocket Broadcasting: Use SendToWebSocket to push data to specific requests or filtered sessions.
    • Asynchronous Handling: In a WebSocket context, calling .Async() marks the result as asynchronous.
    // Accessing session data via the context indexer
    context["user_id"] = 123;
    var userId = context["user_id"];
    
    // Sending a result (HTTP response or WebSocket frame)
    context.Result(new { message = "Success", code = 200 });
  9. Configure HTTPS/SSL

    master

    You can enable SSL via a configuration file (HttpConfig.json) or directly in code via the ServerConfig object.

    // HttpConfig.json
    {
     "SSL": true,
     "CertificateFile": "you.com.pfx",
     "CertificatePassword": "******"
    }
    // Via Code
    mApiServer.ServerConfig.SSL = true;
    mApiServer.ServerConfig.CertificateFile = "you.com.pfx";
    mApiServer.ServerConfig.CertificatePassword = "******";
  10. Call the Hello and GetTime API endpoints

    master

    The API endpoints can be invoked by passing the URL and parameters in a JSON request format.

    For the Hello endpoint, use the name parameter. For the GetTime endpoint, no parameters are required.

    // Request for /Hello
    {
          url: '/Hello', 
          params: { name: 'test' }
    }
    
    // Request for /GetTime
    {
          url: '/GetTime', 
          params: { }
    }
  11. Use Filters and Parameter Validation

    master

    Filters

    Implement FilterAttribute to create custom filters. You can apply them to specific methods using [CustomFilter] or to entire controllers. Use [SkipFilter(typeof(FilterType))] to bypass a specific filter.

    Parameter Validation

    Use specialized attributes to validate input parameters directly in the method signature:

    • [StringRegion(Min=x, Max=y)]
    • [DateRegion(Min=..., Max=...)]
    • [EmailFormater]
    • [IPFormater]
    • [NumberRegion(Min=x, Max=y)]
    // Custom Filter
    public class GlobalFilter : FilterAttribute
    {
        public override bool Executing(ActionContext context) { return base.Executing(context); }
        public override void Executed(ActionContext context) { base.Executed(context); }
    }
    
    // Usage
    [Controller]
    [CustomFilter]
    public class ControllerTest { }
    
    // Validation
    public bool Register(
          [StringRegion(Min = 5)] string name,
          [EmailFormater] string email,
          [NumberRegion(Min = 18, Max = 56)] int age
    )
    {
        return true;
    }
  12. Handle Data Binding (JSON, Form, Multipart)

    master

    BeetleX.FastHttpApi supports several data binding formats using specific attributes:

    • JSON: Use [JsonDataConvert] to bind JSON bodies to parameters or objects.
    • x-www-form-urlencoded: Use [FormUrlDataConvert].
    • multipart/form-data: Use [MultiDataConvert] to handle file uploads via context.Request.Files.
    • Raw Stream: Use [NoDataConvert] to read the raw request stream manually.
    // JSON Binding
    [Post]
    [JsonDataConvert]
    public object Post(string name, string value, IHttpContext context)
    {
        return $"{name}={value}";
    }
    
    // Multipart/Form-Data (File Upload)
    [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 remark;
    }
    
    // Raw Stream
    [Post]
    [NoDataConvert]
    public object PostStream(IHttpContext context)
    {
        string value = context.Request.Stream.ReadString(context.Request.Length);
        return value;
    }