Coder Social home page Coder Social logo

alphacloud / messagepack Goto Github PK

View Code? Open in Web Editor NEW
7.0 2.0 3.0 254 KB

MessagePack formatters for ASP.NET Core MVC

License: MIT License

C# 100.00%
message-pack mvc-core content-negotiation asp-net-core net-core messagepack msgpack messagepack-formatters mvc-formatters httpclient serialization

messagepack's Introduction

MessagePack Formatters for ASP.NET Core MVC and HttpClient

Allows to use MessagePack format with ASP.NET Core MVC. If multiple formatters are configured, content negotiation is used to determine which formatter to use.

This library leverages MessagePack-CSharp library by Yoshifumi Kawai (a.k.a. neuecc).

Build status

Stable Pre-release
Build Master PreRelease
NuGet ASP.NET Core MVC formatters NuGet NuGet
NuGet MediaTypeFormatter for HttpClient NuGet NuGet

Packages

ASP.NET Core MVC formatters

Installation

Install-Packagge Alphacloud.MessagePack.AspNetCore.Formatters

Features

  • Input formatter (decode MessagePack payload).
  • Output formatter (encode MessagePack payload).
  • Source link support (source code on demand in debugger).

Usage

Default configuration

Default configuration uses application/x-msgpack as media typeidentificator, msgpack as file name extension and ContractlessStandardResolver.

Add services.AddMessagePack(); call to your Startup.cs / ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddMessagePack();
    // ...
}

MVC Core (ASP.NET Core 2.x)

When using minimal MVC configuration (e.g. in WebAPI service) only base services are added by default. You are responsible for configuring each of the service you are going to use.

Note: order of formatters is important - in the example below Json will be default serializer, unless MVC is configured to reject requests with unsupported media type.

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvcCore(options =>
    {
        // ...
    })
    .AddDataAnnotations()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.Culture = CultureInfo.InvariantCulture;
        options.SerializerSettings.Formatting = Formatting.None;
    })
    .AddFormatterMappings()
    .AddJsonFormatters()
    .AddXmlSerializerFormatters()
    .AddMsgPackFormatters()
    ;
}

Custom configuration

Default configuration can be changed by providing callback to AddMessagePack method.

Available settings:

  • MediaTypes - allows to specify additional media handled by MessagePack formatters. Default is application/x-msgpack.
  • FormatterResolver - allows to customize serialization, see MsgPack object serialization for details.
  • FileExtensions - allows to specify reponse format URL mapping. Default is msgpack. See sample project or Microsoft Docs for more information.
  • Compression - allows to specify LZ4 compression for messages.
  • UseOldSpecification - write message using old specification compatibility mode. Reading will support both old and new specifications. See Message Pack format specification.
  • OmitAssemblyVersion - don't write assembly version and public key token when using typeless formatter.
  • AllowAssemblyVersionMismatch - allows assembly version mistmatch when loading types during deserialization.
services.AddMessagePack(opt =>
  {
      opt.MediaTypes.Clear();
      opt.MediaTypes.Add("application/x-messagepack");
      opt.FileExtensions.Add("messagepack");
      opt.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Instance;
  })

MediaTypeFormatter for HttpClient

Microsoft.AspNet.WebApi.Client package contains adds support for formatting and content negotiation to System.Net.Http. It allows to add custom content serializers by extending MediaTypeFormatter class.

Installation

Install-Package Alphacloud.MessagePack.HttpFormatter

Usage

Sending request

Library contains two extension methods PostAsMsgPackAsync and PutAsMsgPackAsync. To serialize payload ContractlessStandardResolver is used, which gives a JSON-like experience.

var response = await httpClient.PostAsMsgPackAsync(uri, payload, cancellationToken).ConfigureAwait(false);

Reading response

To deserialize Msgpack response, formatter must be added to formatters collection passed to ReadAsAsync extension method.

This is recommeded method as it enables content negotiation.

var res = await response.Content.ReadAsAsync<TestModel>(_formatters, CancellationToken.None);

if you are expecting only MsgPack content, use MsgPackHttpContentExtensions.ReadMsgPackAsAsync() for HttpContent.

Samples

Sample application is located at src/samples/NetCoreWebApi. Sample Postman requests can be found at src/samples/MessagePack.postman_collection.json. To post MessagePack content, use SingleModel.msgpack located under src/samples.

References

messagepack's People

Contributors

cd21h avatar dependabot-preview[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

messagepack's Issues

BREAKING: Remove .NET Core 3.0 and .NET Core 2.2 support

Remove .NET Core 3.0 and 2.2 as they are out of support.
Remove obsolete classes

  • Alphacloud.MessagePack.AspNetCore.Formatters.MessagePackMvcBuilderExtensions - use IServiceCollection.AddMessagePack() instead of removed IMvcBuilder.AddMessagePackFormatters() or IMvcCoreBuilder.AddMessagePackFormatters()

Drop .NET Core 3.1

Drop .NET Core 3.1

.NET Core 3.1 reaches it's end of life support in December 2022

Improve performance of SerializableTypeCache

Replace ImmutableDictionary with double-checked locking Dictionary.

Type checking is read-heavy and will operate with finite set of types, so lock-free dictionary can be used.

Compression in PostAsMsgPackAsync

Hi,

I can't seem to figure out how to enable compression when using PostAsMsgPackAsync. Am I overlooking something or is this not supported?

Upgrade .NET 5 dependencies

  • Upgrade Microsoft.AspNetCore.Mvc.NewtonsoftJson 5.0.2
  • Upgrade Microsoft.AspNetCore.TestHost to 5.0.2
  • Upgrade System.IO.Pipelines 5.0.1

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.