Messagepack
MessagePack formatters for ASP.NET Core MVC
Install / Use
/learn @alphacloud/MessagepackREADME
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 | |
|
| NuGet ASP.NET Core MVC formatters |
|
|
| NuGet MediaTypeFormatter for HttpClient |
|
|
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 isapplication/x-msgpack.FormatterResolver- allows to customize serialization, see MsgPack object serialization for details.FileExtensions- allows to specify reponse format URL mapping. Default ismsgpack. 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 format https://msgpack.org/index.html
- MessagePack-CSharp https://github.com/neuecc/MessagePack-CSharp
- AddMVC vs AddMvcCore
- https://www.stevejgordon.co.uk/aspnetcore-anatomy-deep-dive-index
- https://offering.solutions/blog/articles/2017/02/07/difference-between-addmvc-addmvcore/
- Content negotiation in ASP.NET Core MVC https://code-maze.com/content-negotiation-dotnet-core/
- Microsoft.AspNet.WebApi.Client https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/
- Source Link - https://github.com/ctaggart/SourceLink
- Postman https://www.getpostman.com/downloads/
Related Skills
docs-writer
99.5k`docs-writer` skill instructions As an expert technical writer and editor for the Gemini CLI project, you produce accurate, clear, and consistent documentation. When asked to write, edit, or revie
model-usage
341.0kUse CodexBar CLI local cost usage to summarize per-model usage for Codex or Claude, including the current (most recent) model or a full model breakdown. Trigger when asked for model-level usage/cost data from codexbar, or when you need a scriptable per-model summary from codexbar cost JSON.
project-overview
FlightPHP Skeleton Project Instructions This document provides guidelines and best practices for structuring and developing a project using the FlightPHP framework. Instructions for AI Coding A
ddd
Guía de Principios DDD para el Proyecto > 📚 Documento Complementario : Este documento define los principios y reglas de DDD. Para ver templates de código, ejemplos detallados y guías paso
