代码之家  ›  专栏  ›  技术社区  ›  Gqqnbig

从控制器获取JsonOptions

  •  1
  • Gqqnbig  · 技术社区  · 7 年前

    我在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 回复  |  直到 7 年前
        1
  •  4
  •   Kirk Larkin    7 年前

    IOptions<MvcJsonOptions> 进入你的控制器,就像这样:

    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

        2
  •  0
  •   Marcus Höglund    7 年前

    一种方法是创建一个类,在其中声明当前配置值

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

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