【问题标题】:Get JsonOptions from controller从控制器获取 JsonOptions
【发布时间】:2018-08-30 04:55:37
【问题描述】:

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


    【解决方案1】:

    您可以将IOptions<MvcJsonOptions> 的实例注入您的控制器,如下所示:

    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 函数。

    【讨论】:

    • 为了记录,一个构造函数可以有多个IOptions参数。
    【解决方案2】:

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

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

    【讨论】:

    • 如果我的控制器的构造函数已经接受了一个whateverConfig,构造函数是否可以接受两个选项,比如public HomeController(WhateverConfig wc, MvcConfig mvcConfig)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2013-08-17
    相关资源
    最近更新 更多