从控制器获取JsonOptions

时间:2018-08-30 04:55:37

标签: c# asp.net-core asp.net-core-2.0

我在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;
    }
}

2 个答案:

答案 0 :(得分:2)

您只需将IOptions<MvcJsonOptions>的实例注入到Controller中,就像这样:

private readonly MvcJsonOptions _jsonOptions;

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

// ...

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

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

如果您只关心Formatting,则可以稍微简化一下,只需使用bool字段即可,

private readonly bool _isIndented;

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

在此示例中,不需要GetIsIndented函数。

答案 1 :(得分: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;
    }
}