user746461
user746461

Reputation:

Get JsonOptions from controller

I set to indent JSON in Startup class, but how do I retrieve the formatting value from a controller?

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
                .AddWebApiConventions()
                .AddJsonOptions(options=> options.SerializerSettings.Formatting=Newtonsoft.Json.Formatting.Indented);
    }

}


public class HomeController : Controller
{
    public bool GetIsIndented()
    {
        bool isIndented = ????
        return isIndented;
    }
}

Upvotes: 4

Views: 1764

Answers (2)

Kirk Larkin
Kirk Larkin

Reputation: 93233

You can just inject an instance of IOptions<MvcJsonOptions> into your Controller, like so:

private readonly MvcJsonOptions _jsonOptions;

public HomeController(IOptions<MvcJsonOptions> jsonOptions, /* ... */)
{
    _jsonOptions = jsonOptions.Value;
}

// ...

public bool GetIsIdented() =>
    _jsonOptions.SerializerSettings.Formatting == Formatting.Indented;

See the docs for more information about IOptions (the Options pattern).

If all you care about is the Formatting, you can simplify slightly and just use a bool field, like so:

private readonly bool _isIndented;

public HomeController(IOptions<MvcJsonOptions> jsonOptions, /* ... */)
{
    _isIndented = jsonOptions.Value.SerializerSettings.Formatting == Formatting.Indented;
}

In this example, there's no need for the GetIsIndented function.

Upvotes: 5

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16846

One option is to create a class where you declare the current configuration values

public class MvcConfig
{
    public Newtonsoft.Json.Formatting Formatting { get; set; }
}

Then instantiate it in the configure method where you also register the class as a singleton

public void ConfigureServices(IServiceCollection services)
{
    var mvcConfig = new MvcConfig
    {
        Formatting = Newtonsoft.Json.Formatting.Indented
    };

    services.AddMvc()
            .AddWebApiConventions()
            .AddJsonOptions(options=> options.SerializerSettings.Formatting=mvcConfig.Formatting);

    services.AddSingleton(mvcConfig);
}

Then inject it in the controller and use it

public class HomeController : Controller
{
    private readonly MvcConfig _mvcConfig;
    public HomeController(MvcConfig mvcConfig)
    {
        _mvcConfig = mvcConfig;
    }
    public bool GetIsIndented()
    {
        return _mvcConfig.Formatting == Newtonsoft.Json.Formatting.Indented;
    }
}

Upvotes: 0

Related Questions