neuecc / Utf8Json

Definitely Fastest and Zero Allocation JSON Serializer for C#(NET, .NET Core, Unity, Xamarin).
MIT License
2.36k stars 266 forks source link

UTF8Json ASP.NET Core formatters issue #103

Open saibaskaran57 opened 6 years ago

saibaskaran57 commented 6 years ago

Hello there,

I've been facing issues trying to implement UTF8Json Formatter using Utf8Json.AspNetCoreMvcFormatter package in conjunction with built-in XML formatter.

I went on to further find the root-cause of the issue: https://github.com/neuecc/Utf8Json/blob/master/src/Utf8Json.AspNetCoreMvcFormatter/Formatter.cs

The formatter above uses the below which always return true(on CanWriteResult, which defaults to JSON) and does not honor any Accept headers(e.g. XML, MessagePack):

public bool CanWriteResult(OutputFormatterCanWriteContext context)
{
    return true;
}

In order to reproduce it, just implement as per the below and use different Accept headers:

services.AddMvc(options =>
{
    options.RespectBrowserAcceptHeader = true;
    options.ReturnHttpNotAcceptable = true;

    options.InputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter>();
    options.InputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.JsonPatchInputFormatter>();
    options.OutputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter>();

    options.InputFormatters.Add(new JsonInputFormatter());
    options.OutputFormatters.Add(new JsonOutputFormatter());

    options.InputFormatters.Add(new Microsoft.AspNetCore.Mvc.Formatters.XmlDataContractSerializerInputFormatter(options));
    options.OutputFormatters.Add(new Microsoft.AspNetCore.Mvc.Formatters.XmlDataContractSerializerOutputFormatter());

    options.InputFormatters.Add(new MessagePackInputFormatter());
    options.OutputFormatters.Add(new MessagePackOutputFormatter());
});

From Microsoft documentation, it's suggested to use TextInputFormatter and TextOutputFormatteras the base class for custom formatters.

Therefore, I have implemented as per the suggestion with references from Formatter.cs by UTF8Json and i got it working successfully.

Here are the sample reference to get it working with different Accept types: https://github.com/saibaskaran57/ContentFormatterApp/blob/master/src/ContentFormatterApp/ContentFormatterApp/Formatters/

If we agree that this is a issue, i'll be happy to make a PR for this change.

OlegNadymov commented 6 years ago

It's definitely helpful! Just one moment.

For binary types, derive from the InputFormatter or OutputFormatter base class. https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/custom-formatters?view=aspnetcore-2.1#derive-from-the-appropriate-base-class

So you should have changed it for MessagePack formatters.

saibaskaran57 commented 6 years ago

That's right. Should have been on a note though.

That should inherit from InputFormatter or OutputFormatter base class for MessagePack formatters.