Giter Club home page Giter Club logo

nancy.serialization.hyperion's Introduction

Nancy.Serialization.Hyperion

Implementations of the ISerialization and IBodyDeserializer interfaces, based on Hyperion, for Nancy

Stable
Package Build Status

Supported Platforms

Continuous integration

Windows Linux
Build Build Status Build Status

Using with Asp.Net Core and Owin

Start of by installing the Nancy, Nancy.Serialization.Hyperion, Microsoft.AspNetCore.Owin nuget packages

Configure your Startup.cs as below

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<Serializer>(provider =>
        {
            HyperionSerializerSettings hyperionSerializerSettings = HyperionSerializerSettings.Default;

            return new Serializer(new SerializerOptions(preserveObjectReferences: hyperionSerializerSettings.PreserveObjectReferences,
                                                        versionTolerance: hyperionSerializerSettings.VersionTolerance,
                                                        ignoreISerializable: hyperionSerializerSettings.IgnoreISerializable));
        });

        // If using Kestrel:
        services.Configure<KestrelServerOptions>(options => { options.AllowSynchronousIO = true; });

        // If using IIS:
        services.Configure<IISServerOptions>(options => { options.AllowSynchronousIO = true; });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseOwin(action => action.UseNancy(options => options.Bootstrapper = new DemoBootstrapper(app.ApplicationServices, env)));
    }
}

Then we need to create our DemoBootstrapper.cs which responsible for both registering HyperionProcessor to Nancy configuration and registering Hyperion serializer to TinyIoCContainer.

public class DemoBootstrapper : DefaultNancyBootstrapper
{
    private readonly IServiceProvider _serviceProvider;
    private readonly IWebHostEnvironment _webHostEnvironment;

    public DemoBootstrapper(IServiceProvider serviceProvider, IWebHostEnvironment webHostEnvironment)
    {
        _serviceProvider = serviceProvider;
        _webHostEnvironment = webHostEnvironment;
    }

    protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration
    {
        get
        {
            Type[] processors = {typeof(ViewProcessor), typeof(HyperionProcessor), typeof(JsonProcessor), typeof(XmlProcessor)};

            return NancyInternalConfiguration.WithOverrides(x => x.ResponseProcessors = processors);
        }
    }

    public override void Configure(INancyEnvironment environment)
    {
        if (_webHostEnvironment.IsDevelopment())
        {
            environment.Tracing(true, true);
        }
    }

    protected override void ConfigureApplicationContainer(TinyIoCContainer container)
    {
        base.ConfigureApplicationContainer(container);

        container.Register(_serviceProvider.GetRequiredService<Serializer>());
    }
}

NancyModule example

When Nancy detects that the HyperionSerializer and HyperionBodyDeserializer types, it will assume you want to use them for application/x-hyperion content types.

public sealed class HomeModule : NancyModule
{
    public HomeModule()
    {
        Get("/user", args =>
        {
            var user = new User() {Id = Guid.NewGuid(), Name = "Ozgen", Age = 32, CreateDate = DateTime.Now};

            // return Response.AsHyperion<User>(user);

            return user;
        });

        Post("/user", o =>
        {
            var user = this.Bind<User>();

            return "OK";
        });
    }
}

Client request example

Start of by installing the Hyperion nuget

private static async Task Main(string[] args)
{
    var serializer = new Serializer(new SerializerOptions(preserveObjectReferences: true, versionTolerance: true, ignoreISerializable: true));

    var user = new User() {Id = Guid.NewGuid(), Name = "Deniz", Age = 31, CreateDate = DateTime.Now};

    using var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-hyperion"));

    var uri = new Uri("<adress>/user");

    using (var stream = new MemoryStream())
    {
        serializer.Serialize(user, stream);

        byte[] content = stream.ToArray();
        var byteArrayContent = new ByteArrayContent(content);
        byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-hyperion");

        HttpResponseMessage postAsync = await client.PostAsync(uri, byteArrayContent);
    }

    HttpResponseMessage getAsync = await client.GetAsync(uri);

    Stream responseAsync = await getAsync.Content.ReadAsStreamAsync();

    user = serializer.Deserialize<User>(responseAsync);
}

See Nancy.Demo.AspNet.Application and Nancy.Demo.Console.Client sandbox applications for details.

Custom Nancy components for Hyperion

License

Licensed under MIT, see LICENSE for the full text.

nancy.serialization.hyperion's People

Contributors

blind-striker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

blind-striker

nancy.serialization.hyperion's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.