Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

LightNode

> 编程语言
Open source

Micro RPC/REST Framework built on OWIN

181 stars0 likes7 views
WebsiteGitHub

About

Micro RPC/REST Framework built on OWIN

LightNode

LightNode is a Micro RPC/REST Framework built on OWIN. LightNode is a good alternative to the ASP.NET Web API and Nancy if you make a simple API. It is like Ruby's Grape framework, Slack API's HTTP RPC-style methods. Implementation of the API is lightweight, powerful debugging supports with Glimpse, client code generation by T4 for PCL(HttpClient) and Unity3D.

Update(2016-07-28), for ASP.NET Core

LightNode 2 has been started. You can install from -Pre packages.

PM> Install-Package LightNode -Pre

Simple ASP.NET Core Startup

csharp
using LightNode;

public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseLightNode(typeof(Startup));
    }
}

LightNode 2 includes swagger package. You can map for Swagger.

…

Installation

binary from NuGet, LightNode.Server

PM> Install-Package LightNode.Server

Implement Server

Server implementation is very easy, built up Owin and implements LightNodeContract.

…

Compile, run, very quick! LightNode calls class as Contract, method as Operation.

Parameter model bindings supports only basic pattern, can't use complex type. allow types are "string, DateTime, DateTimeOffset, Boolean, Decimal, Char, TimeSpan, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, SByte, Byte, Enum and each Nullable types and array(except byte[]. If you want to use byte[], use Base64 string instead of byte[] or see receive byte[] section)

Return type allows all serializable(ContentFormatter support) type.

Filter

LightNode supports filter. The implementation is like middleware pipeline.

csharp
public class SampleFilterAttribute : LightNodeFilterAttribute
{
    public override async Task Invoke(OperationContext operationContext, Func next)
    {
        try
        {
            // OnBeforeAction

            await next(); // next filter or operation handler

            // OnAfterAction
        }
        catch
        {
            // OnExeception
        }
        finally
        {
            // OnFinally
        }
    }
}

Filter can be attached contract(class), operation(method) and global. Execution pipeline is formed is sorted by Order all specified. Range is -int.MaxValue to int.MaxValue. Default Order of all filters is int.MaxValue.

Difference between Middleware and Filter is who knows operation context. Filter is located after the parameter binding. Therefore, it is possible check attributes(operationContext.IsAttributeDefined, operationContext.GetAttributes).

Control StatusCode

The default status code, can't find operation returns 404, failed operation returns 500, success and has value returns 200, success and no value returns 204. If returns arbitrary status code, throw ReturnStatusCodeException.

csharp
throw new ReturnStatusCodeException(System.Net.HttpStatusCode.Unauthorized);

Glimpse plugin

LightNode fully supports Glimpse! Currently Glimpse does not support Owin but if you host on Microsoft.Owin.Host.SystemWeb Glimpse works. You can download Glimpse plugin from NuGet.

  • PM> Install-Package Glimpse.LightNode

There are configuration sample.

csharp
public void Configuration(Owin.IAppBuilder app)
{
    app.EnableGlimpse(); // This is Glimpse.LightNode's helper for enable Glimpse
    app.MapWhen(x => !x.Request.Path.Value.StartsWith("/glimpse.axd", StringComparison.OrdinalIgnoreCase), x =>
    {
        x.UseLightNode(new LightNodeOptions()
        {
            // for Glimpse Profiling
            OperationCoordinatorFactory = new GlimpseProfilingOperationCoordinatorFactory()
        });
    });
}

Access glimpse.axd and Click Standalone Glimpse Launch Now! Click History window and Inspect. You can see Filter and Execution elapsed on Timeline tab.

Check the LightNode tab, you can monitor everything. Parameters, Result, Exectuion Phase, Response, and LightNodeOptions.

If encounts exception, LightNode tab shows exception on Result.

My recommended glimpse configuration.

xml

    
        
            
            
            
            
        
    
    
        
            
            
            
            
            
            
            
            
        
    

Ignore ControlCookiePolicy is very important. But we can't indistinguishable request. Glimpse handle group by cookie. You can add glimpseid cookie for example

csharp
var req = WebRequest.CreateHttp("http://localhost:41932/Member/Random?seed=13");

req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(new Uri("http://localhost:41932"), new Cookie("glimpseid", "UserId:4"));

Swagger Integration

LightNode supports Swagger for API Explorer(currently Swagger supports is experimental, only shows parameters).

Middleware available in NuGet.

  • PM> Install-Package LightNode.Swagger

Swagger-UI file is embedded in LightNode.Swagger. You can enable only UseLightNodeSwagger.

…

Okay, for example jump to http://localhost:41932/Swagger/, you can see all API info and Swagger specification json can download from api-default.json. If you host multiple LightNode engine, you can select target engine from {engineID}.json. {engineID} is from ILightNodeOptions.ServerEngineId.

If you can't run swagger on hosting IIS, maybe conflicts static file handling. Please remoe StaticFile handler and register OwinHttpHandler for all paths.

csharp

    
        
        
        
        
    

If you want to customize index.html(or others) for authentication etc. You can use ResolveCustomResource.

…

with ASP.NET MVC

You can use LightNode with ASP.NET MVC. A simple solution is to change the root path.

csharp
public void Configuration(IAppBuilder app)
{
    app.Map("/api",  x =>
    {
        x.UseLightNode();
    });
}

More ContentFormatter

Default content formatter is JavaScriptContentFormatter(application/json) and bundling formatters are TextContentFormatter(text/plain), HtmlContentFormatter(text/html), RawOctetStreamContentFormatter(application/octet-straem), XmlContentFormatter(application/xml), DataContractContentFormatter(application/xml), DataContractJsonContentFormatter(application/json).

More useful ContentFormatters(for JsonNet(JSON), Jil(JSON/JSON+GZip), Jil+LZ4, ProtoBuf, MsgPack) are available.

  • PM> Install-Package LightNode.Formatter.JsonNet
  • PM> Install-Package LightNode.Formatter.Jil
  • PM> Install-Package LightNode.Formatter.Jil.LZ4
  • PM> Install-Package LightNode.Formatter.ProtoBuf
  • PM> Install-Package LightNode.Formatter.MsgPack

Configuration sample

…

Receive(or Send) byte[]

LightNode isn't allow byte[] argument. If you want to receive byte[] that use Base64 string instead of byte[]. But you needs to avoid Base64, you can take raw stream from Environment.

csharp
[Post, IgnoreClientGenerate]
public int PostByte() // zero argument
{
    // Take raw stream
    var body = this.Environment["owin.RequestBody"] as Stream;
    byte[] bodyBytes;
    using (var ms = new MemoryStream())
    {
        body.CopyTo(ms);
        bodyBytes = ms.ToArray();
    }
    return bodyBytes.Length;
}

If you want to receive multipart/form-data, you can parse by ReadAsMultipartAsync of System.Net.Http.Formatting.dll.

csharp
var body = this.Environment["owin.RequestBody"] as Stream;
var multipart = await new StreamContent(body).ReadAsMultipartAsync();

If you return byte[] array, you maybe should avoid Json(or other) ContentFormatter. You can use RawOctetStreamContentFormatterFactory.

csharp
[IgnoreClientGenerate]
[OperationOption(AcceptVerbs.Post, typeof(RawOctetStreamContentFormatterFactory))]
public byte[] EchoByte()
{
    var body = this.Environment["owin.RequestBody"] as Stream;
    byte[] bodyBytes;
    using (var ms = new MemoryStream())
    {
        body.CopyTo(ms);
        bodyBytes = ms.ToArray();
    }
    return bodyBytes;
}

Return HTML

If you needs return html, set content formatter to HtmlContentFormatter/HtmlContentFormatterFactory. If you needs template engine, you can use RazorEngine. Simple helper base contract.

…

And you can make shortcut of OperationOptionAttribute.

public class Html : LightNode.Server.OperationOptionAttribute
{
    public Html(AcceptVerbs acceptVerbs = AcceptVerbs.Get | AcceptVerbs.Post)
        : base(acceptVerbs, typeof(HtmlContentFormatterFactory))
    {

    }
}

Language Interoperability

LightNode is like RPC but REST. Public API follows a simple rule. Address is {ClassName}/{MethodName}, and it's case insensitive. GET parameter use QueryString. POST parameter use x-www-form-urlencoded. Response type follows configured ContentFormatter. Receiver can select response type use url extension(.xml, .json etc...) or Accept header.

Authentication, Session, Caching, Routing, Versioning, etc

You can use other OWIN Middleware(for example ASP.NET Identity). LightNode can copmose with there. LightNode provides only core framework.

LightNode can enable per assembly. For the versioning strategy with project separating.

csharp
app.Map("/v1", x =>
{
    x.UseLightNode(new LightNodeOptions(), typeof(v1Contract).Assembly);
});

app.Map("/v2", x =>
{
    x.UseLightNode(new LightNodeOptions(), typeof(v2Contract).Assembly);
});

Client code generation

Client side implementation of the REST API is often painful. LightNode solves by T4 code generation.

…

csharp var option = new LightNodeOptions { Logger = LightNode.Diagnostics.LightNodeEventSource.Log }; app.UseLightNode(option);

…

csharp // Default var option = new LightNodeOptions() { ErrorHandlingPolicy = ErrorHandlingPolicy.ThrowException, OperationMissingHandlingPolicy = OperationMissingHandlingPolicy.ReturnErrorStatusCodeIncludeErrorDetails, }; app.UseLightNode(option);

 
Performance
---
LightNode is fastest framework.

Performance source code is in [LightNode/Performance](https://github.com/neuecc/LightNode/tree/master/Performance). Enviroment is "Windows 8.1/CPU Core i7-3770K(3.5GHz)/Memory 32GB" and disabled firewall and windows defender. Orange and Green bar is hosted on IIS(System.Web). LightNode(Green bar)'s performance is nearly raw handler. Gray bar is reference, LightNode on [Helios - Microsoft.Owin.Host.IIS](http://www.nuget.org/packages/Microsoft.Owin.Host.IIS/) gots extremely performance. 

Build/Test Status
---
LightNode is using [AppVeyor](http://www.appveyor.com/) CI. You can check unit test status.

ReleaseNote
---
1.6.6.1, 2.0.4-beta
* Add byte[] support with MultiPartContent

1.6.5.1, 2.0.3-beta
* Add PassThroughWhenStatusCodesAre option

2.0.0-beta - 2016-07/28
* ASP.NET Core support

1.6.4 - 2015-11-27
* Only LightNode.Swagger, fix doesn't show swagger when with selfhost

1.6.3 - 2015-10-06
* Add ReturnStatusCodeException(EnvironmentEmitter)
* Add DebugOnlyClientGenerateAttribute
* Fix DefaultParameter for bool create True/False

1.6.2(Only LightNode.MsgPack) - 2015-08-18
* Fix MsgPackFormatter when Serialize null then throws Exception
* Update dependency to MsgPack-CLI 0.6.1

1.6.1 - 2015-08-11
* Fix when Contract's r

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言