使用AddMvcCore配置JsonOutputFormatter

时间:2017-04-13 15:08:26

标签: asp.net asp.net-mvc asp.net-core asp.net-core-mvc

我正在尝试设置细长的ASP.NET核心管道并使用AddMvcCore而不是AddMvc。我主要是从AddMvc复制了这个,省略了Razor相关项目:

public void ConfigureServices(IServiceCollection services) =>
    services
        .AddMvcCore(
            options => 
            {
                // JsonOutputFormatter not found in OutputFormatters!
                var jsonOutputFormatter = 
                    options.OutputFormatters.OfType<JsonOutputFormatter>.First();
                jsonOutputFormatter.SupportedMediaTypes.Add("application/ld+json");
            })
        .AddApiExplorer()
        .AddAuthorization()
        .AddFormatterMappings()
        .AddRazorViewEngine()
        .AddRazorPages()
        .AddCacheTagHelper()
        .AddDataAnnotations()
        .AddJsonFormatters()
        .AddCors();

我想向JsonOutputFormatter添加MIME类型,但无法在OutputFormatters集合中找到它。也就是说,应用仍然可以输出JSON,所以我认为JsonOutputFormatter将在以后添加。我怎样才能掌握JsonOutputFormatter?

2 个答案:

答案 0 :(得分:2)

最后可以使用AddMvcOptions(位置很重要)在添加JSON格式化程序后访问它们:

services
    .AddMvcCore()
    .AddJsonFormatters()
    .AddMvcOptions(options => { // do your work here });

答案 1 :(得分:1)

public void ConfigureServices(IServiceCollection services) =>
services
    .AddMvcCore(
        options => 
        {
            var jsonOutputFormatter = options.OutputFormatters.FirstOrDefault(p => p.GetType() == typeof(JsonOutputFormatter)) as JsonOutputFormatter;

            // Then add
            jsonOutputFormatter?.SupportedMediaTypes.Add("application/ld+json");
        })
    .AddApiExplorer()
    .AddAuthorization()
    .AddFormatterMappings()
    .AddRazorViewEngine()
    .AddRazorPages()
    .AddCacheTagHelper()
    .AddDataAnnotations()
    .AddJsonFormatters()
    .AddCors();