首页 新闻 搜索 专区 学院

ASP.NET Core Web API 项目中使用 services.AddMvcCore 的问题

0
悬赏园豆:30 [已解决问题] 解决于 2018-12-21 12:18

如果在 Startup.ConfigureServices 中使用 services.AddMvcCore() ,访问时会出现下面的错误:

'Microsoft.AspNetCore.Mvc.MvcOptions.InputFormatters' must not be empty. At least one 'Microsoft.AspNetCore.Mvc.Formatters.IInputFormatter' is required to bind from the body.
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinderProvider.GetBinder(ModelBinderProviderContext context)

请问如何解决?

dudu的主页 dudu | 高人七级 | 园豆:38815
提问于:2018-12-21 10:11
< >
分享
最佳答案
0

看了一下AddMvc的源码,我觉得你应该还要加上一些初始化的东西

        public static IMvcBuilder AddMvc(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            var builder = services.AddMvcCore();

            builder.AddApiExplorer();
            builder.AddAuthorization();

            AddDefaultFrameworkParts(builder.PartManager);

            // Order added affects options setup order

            // Default framework order
            builder.AddFormatterMappings();
            builder.AddViews();
            builder.AddRazorViewEngine();
            builder.AddRazorPages();
            builder.AddCacheTagHelper();

            // +1 order
            builder.AddDataAnnotations(); // +1 order

            // +10 order
            builder.AddJsonFormatters();

            builder.AddCors();

            return new MvcBuilder(builder.Services, builder.PartManager);
        }
收获园豆:30
MrNice | 老鸟四级 |园豆:3021 | 2018-12-21 12:02

加上 AddJsonFormatters 即可

services.AddMvcCore().AddJsonFormatters();
dudu | 园豆:38815 (高人七级) | 2018-12-21 12:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册