如何将Json Formatters添加到MvcCore? - c#

我正在跟踪下一个tutorial of IdentityServer4 implementation for API,但是无法将方法AddJsonFormatters()调用为services.AddMvcCore()
我目前正在从ASP.NET Core 3.0.0中的空模板配置API

我添加了NuGet包Microsoft.AspNetCore.Mvc.Formatters.Json,但没有结果。
另外,我知道使用AddMvc()代替AddMvcCore()是部分解决方案,但是我不能在AddAuthorization()上使用AddMvc()

//code extracted from the link
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();
    }
}

这是我在上面看到的错误消息:

“ IMvcCoreBuilder”不包含针对的定义
'AddJsonFormatters',并且没有可访问的扩展方法
'AddJsonFormatters'接受类型的第一个参数
可以找到“ IMVCoreBuilder”(您使用的是缺少的指令还是
组装参考?)

这是方法吗?我应该发送MVCCoreBuilder吗?我怎么做? MvcJsonMvcCoreBuilderExtensions.AddJsonFormatters Method

参考方案

呼叫services.AddMvc()时,您会得到一个IMvcBuilder

如果要添加更多输出或输入格式化程序,则IMvcBuilder具有扩展方法,您可以调用AddMvcOptions,下面有添加的XmlDataContractSerializerOutputFormatter示例

    mvcBuilder.AddMvcOptions(options =>
        {
            options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter(options));

Mvc已经有一个JsonOutputFormatter,因此您可以在AddMvcOptions内部获取它,并在需要时添加自己的自定义媒体类型。

var jsonOutputFormatter = options.OutputFormatters.OfType<JsonOutputFormatter>().FirstOrDefault();

        if (jsonOutputFormatter != null)
        {
            jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.Vnd+json.all);
            jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.ApplicationOctetStream);
        }

如何在ASP.NET Core Web应用程序中增加JSON反序列化MaxDepth限制 - c#

我们正在将ASP.NET Core 2.1与.NET Framework 4.6.2结合使用。我们有一个客户需要向我们的Web应用程序发送一个很大程度上嵌套的json结构。当他们进行此调用时,我们将输出以下日志并返回错误: 读取器的MaxDepth超过了32。路径“ super.long.path.to property”,第1行,位置42111。”我浏览了…

从Axios请求以ASP.NET Core API返回下载文件 - c#

大家好我正在尝试从Axios Request从ASP.NET Core Web API下载文件。这是我的示例API方法。 (基于此stackoverflow question的代码)[HttpPost("download")] public async Task<IActionResult> DownloadFile(){ .…

从.NET Core 2.1降级到.NET 4.7.1时,如何使用IApplicationBuilder和IServiceCollection? - c#

我不得不将我的项目从.NET Core 2.1更改为.NET 4.7.1,并且修复了几乎所有错误,但以下错误仍然困扰着我 “ IApplicationBuilder”不包含“ UseHsts”的定义,也找不到找不到接受类型为“ IApplicationBuilder”的第一个参数的扩展方法“ UseHsts”(是否缺少using指令或程序集引用?) “ IA…

如何获取.NET Core 3单文件应用程序以查找appsettings.json文件? - c#

如何配置单文件.Net Core 3.0 Web API应用程序以查找与建立单文件应用程序相同的目录中的appsettings.json文件?跑步后dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true 该目录如下所示:XX/XX/XXXX XX:XX PM <DIR> . X…

如何在启用了ASP.NET Core 2.2 EndpointRouting的情况下使用RouteDataRequestCultureProvider? - c#

我正在尝试在新的ASP.NET Core 2.2 MVC项目中使用RouteDataRequestCultureProvider。我已经阅读了Routing in ASP.NET Core上的Microsoft文档,以了解2.2中引入的更改,但是我不明白为什么“文化”不被视为URL生成的环境值。我在Startup.cs中更新了ConfigureService…