c# - 如何将 Json 格式化程序添加到 MvcCore?

标签 c# asp.net-core identityserver4

我正在关注下一个 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' does not contain a definition for 'AddJsonFormatters' and no accessible extension method 'AddJsonFormatters' accepting a first argument of type 'IMVCoreBuilder' could be found (are you using a missing directive or an assembly reference?)

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

最佳答案

当你调用services.AddMvc()时,你会得到一个IMvcBuilder

如果您想添加更多输出或输入格式化程序,IMvcBuilder 有一个扩展方法,您可以调用 AddMvcOptions,下面有一个 XmlDataContractSerializerOutputFormatter 示例 已添加<​​/p>

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

关于c# - 如何将 Json 格式化程序添加到 MvcCore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56365319/

相关文章:

c# - 如何在不按 Tab 的情况下强制 DataGridView 当前单元格轮廓

c# - RavenDB 系统数据库物理存储在哪里?

reactjs - 无提示更新错误帧窗口在刷新 token 上超时

identityserver4 - 如何在 IdentityServer4 上的 TestController 上启用 [Authorize] 以声明 CRUD Controller

ajax - 在身份服务器 4 中处理从 MVC 客户端到资源 api 的 ajax 调用中的身份验证

c# - Linq 查询 : Cannot convert type IEnumerable<string> to string changing . ToString() 到(字符串)

c# - Crystal 报表条形码 128 转换器

asp.net-core - 在 .NET Core OpenID Connect 中间件中重定向?

asp.net-core - ServiceProvider 无法解析配置方法中的选项

asp.net-core - Microsoft Application Insights 是否支持 MVC 6 (.Net 5)