我正在使用 Asp.Net Core 3.0 预览版中的服务器端 blazor(Razor 组件)开发网络游戏。我有一个控制器类,用于将游戏数据保存到服务器,但是每当我使用有效的 JSON 正文发出发布请求时,控制器无法格式化请求正文,因为它无法从上下文中找到任何 IInputFormatter。
我已经能够在不使用 [FromBody] 属性的情况下执行简单的 GET 请求和 POST,因此我知道我的控制器路由正在工作。但是每当我尝试使用 HttpClient SendJsonAsync 或 PostJsonAsync 方法并尝试使用 [FromBody] 属性读取 JSON 时,我都会收到以下错误:
System.InvalidOperationException:“Microsoft.AspNetCore.Mvc.MvcOptions.InputFormatters”不能为空。从正文绑定至少需要一个“Microsoft.AspNetCore.Mvc.Formatters.IInputFormatter”。
我还直接将 Microsoft.AspNetCore.Mvc.Formatters.Json 安装到我的项目中,但没有运气。
我在我的 Server.Startup 类中注册并将 mvc 添加到我的服务中
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorComponents<App.Startup>();
services.AddMvc();
//Register httpclient service
if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
{
// Setup HttpClient for server side in a client side compatible fashion
services.AddScoped<HttpClient>(s =>
{
// Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
var uriHelper = s.GetRequiredService<IUriHelper>();
return new HttpClient
{
BaseAddress = new Uri(uriHelper.GetBaseUri())
};
});
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller}/{action}"); });
app.UseRazorComponents<App.Startup>();
}
我的控制器类和方法:
public class GameController : Controller
{
[HttpPost]
[Route("api/Game/SaveGame")]
public string SaveGame([FromBody]GameInfoBody gameInfo)
{
//save the game to database
}
}
我的 Game.cshtml 页面中的客户调用:
public async Task<string> SaveGameToDatabase(GameEngine game)
{
var request = new GameInfoPostModel()
{
gameInfo = new GameInfoBody
{
ID = game.ID,
GameEngine = game,
Players = game.Teams.SelectMany(x => x.Players).Select(x => new PlayerGameMapping() { PlayerID = x.ID }).ToList()
}
};
try
{
var result = await Client.SendJsonAsync<string>(HttpMethod.Post, "/api/Game/SaveGame", request);
return result;
}
catch (Exception e)
{
return "Failed to save" + e.Message;
}
}
完整的堆栈跟踪:
System.InvalidOperationException: '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)
at Microsoft.AspNetCore.Mvc.ModelBinding.ModelBinderFactory.CreateBinderCoreUncached(DefaultModelBinderProviderContext providerContext, Object token)
at Microsoft.AspNetCore.Mvc.ModelBinding.ModelBinderFactory.CreateBinder(ModelBinderFactoryContext context)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.GetParameterBindingInfo(IModelBinderFactory modelBinderFactory, IModelMetadataProvider modelMetadataProvider, ControllerActionDescriptor actionDescriptor, MvcOptions mvcOptions)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.CreateBinderDelegate(ParameterBinder parameterBinder, IModelBinderFactory modelBinderFactory, IModelMetadataProvider modelMetadataProvider, ControllerActionDescriptor actionDescriptor, MvcOptions mvcOptions)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerCache.GetCachedResult(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionInvokerFactory.CreateInvoker(ActionContext actionContext)
at Microsoft.AspNetCore.Mvc.Routing.MvcEndpointDataSource.<>c__DisplayClass22_0.<CreateEndpoint>b__0(HttpContext context)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
阅读文档告诉我 JsonFormatters 默认包含在内。我已经使用 Fiddler 验证了我的调用具有正确的内容类型和有效的 JSON。我想如果它无法从上下文中找到任何 InputFormatters,我一定没有正确配置服务,但我还没有找到其他人遇到这个问题,我不知道下一步该尝试什么。任何帮助将不胜感激,谢谢