从控制器获取JsonOptions

问题描述 投票:1回答:2

我设置在Startup类中缩进JSON,但是如何从控制器中检索格式化值?

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;
    }
}
c# asp.net-core asp.net-core-2.0
2个回答
2
投票

您可以将一个IOptions<MvcJsonOptions>实例注入您的Controller,如下所示:

private readonly MvcJsonOptions _jsonOptions;

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

// ...

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

有关docs(选项模式)的更多信息,请参阅IOptions

如果您关心的只是Formatting,您可以稍微简化并使用bool字段,如下所示:

private readonly bool _isIndented;

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

在这个例子中,不需要GetIsIndented函数。


0
投票

一种选择是创建一个声明当前配置值的类

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

然后在configure方法中实例化它,您也可以将类注册为单例

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);
}

然后将其注入控制器并使用它

public class HomeController : Controller
{
    private readonly MvcConfig _mvcConfig;
    public HomeController(MvcConfig mvcConfig)
    {
        _mvcConfig = mvcConfig;
    }
    public bool GetIsIndented()
    {
        return _mvcConfig.Formatting == Newtonsoft.Json.Formatting.Indented;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.