Home > database >  select OutputFormatter depending on the query parameter
select OutputFormatter depending on the query parameter

Time:09-22

I need to select OutputFormatter depending on the query parameter. How to do that? I am moving from .NET Framework WebApi to .NET Core WebApi. The .NET Framework WebApi had DefaultContentNegotiator class do that:

public class CustomContentNegotiator : DefaultContentNegotiator
{
        
    
    public override ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {       
                //Read query from request object and add output formatters below
                bindFormatters = new List<MediaTypeFormatter>
                {
                    new ConvertResultRawFormatter(),
                    new JsonMediaTypeFormatter
                    {
                        SerializerSettings =
                        {
                            NullValueHandling = NullValueHandling.Ignore
                        }
                    }
                };
            }
    
            return base.Negotiate(type, request, bindFormatters);
        }
}

replace in configuration with new formatted negotiator

 config.Services.Replace(typeof(IContentNegotiator), new CustomContentNegotiator());

CodePudding user response:

Will the custom output formatters not work for you? Read this ms docs

CodePudding user response:

From the comments it seems that the real question is how to add the Content-Disposition: inline header if the URL contains download=inline parameter. This doesn't concern formatting or content negotiation.

There are several ways to add headers to a response. One of them is to add inline middleware that adds the header if the query parameter is present :

app.Use(async (context, next) => 
{
    context.Response.OnStarting(() => 
    {
        var download= context.Request.Query["download"];
        if (download=="inline")
        {
            context.Response.Headers.Add("Content-Disposition", "inline");
        }
    }
}

This affects all routes

  • Related