如何在AspNet Core 1.1中注入MvcJsonOptions?

时间:2017-01-18 15:22:38

标签: asp.net-core

我无法使用静态JsonConvert设置,在我的过滤器中,我需要根据当前MvcJsonOptions格式化字符串:

services.AddMvc().AddJsonOptions(x =>
{
    x.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});

class ReturnBadRequestForInvalidModelFilter : IAsyncActionFilter
    {
        private readonly MvcJsonOptions _options;

        public ReturnBadRequestForInvalidModelFilter(MvcJsonOptions options)
        {
            _options = options;
        }

        ...

        private string FormatPropertyName(string key)
        {
            if (string.IsNullOrEmpty(key))
                return key;

            return _options.SerializerSettings.ContractResolver is CamelCasePropertyNamesContractResolver
                ? char.ToLowerInvariant(key[0]) + key.Substring(1)
                : key;
        }

1 个答案:

答案 0 :(得分:1)

JsonResultExecutor.cs的启发尝试使用IOptions<MvcJsonOptions>

public class YourClass
{
    public MvcJsonOptions JsonOptions { get; set; }

    public YourClass(IOptions<MvcJsonOptions> mvcJsonOptions)
    {
        JsonOptions = mvcJsonOptions.Value;
    }
}