我正在关注下一个 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/