我正在尝试使用.Net Core 3.0预览版中的Blazor服务器端应用程序(RazorComponents)创建多人游戏。我在Server项目中有一个SQL lite数据库和数据访问层,用于存储游戏信息。我在Server项目中也有一个Controller类,可以使用数据访问层从数据库返回对象。我在App项目中的cshtml页面正在进行api调用(使用注入的HttpClient),尝试将其路由到我的控制器,但未到达服务器。
我一直在尝试不同的Http客户端调用,但是似乎没有一个到达控制器。我觉得我缺少明显的东西,或者配置不正确。我没有扎实的Razor / MVC背景,因此这对我来说很难解决。为了进行测试,我试图调用一个返回字符串的简单方法
在App.Game.cshtml @functions {}部分:
private async Task SaveGame()
{
var result = await Client.GetStringAsync("/api/Game/Test");
}
在Server.Controllers.GameController中:
public class GameController : Controller
{
[HttpGet]
[Route("api/Game/Test")]
public string Test()
{
return "test";
}
}
我的Server.Startup文件注册MVC和Http服务,如下所示:
// 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();
//Code I got from internet to 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.UseStaticFiles();
app.UseRazorComponents<App.Startup>();
app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}"); });
}
调用SaveGame()方法并执行客户端调用时,我在输出中看到了这一点:
Microsoft.AspNetCore.Hosting.Internal.GenericWebHostService:信息:请求启动HTTP / 1.1 GET http://localhost:59682/api/Game/Test
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware:信息:正在发送文件。请求路径:“ / index.html”。物理路径:“ {我的游戏路径} .Server \ wwwroot \ index.html”
因此,似乎无法正确路由到控制器。我一直在搜寻其他人是如何做到这一点的,似乎我正在以正确的方式来做。有人知道我想念什么吗?
我一直在关注像这样的教程: http://learn-blazor.com/architecture/rest-api/ https://medium.freecodecamp.org/how-to-create-an-application-using-blazor-and-entity-framework-core-1c1679d87c7e
答案 0 :(得分:0)
尝试一下:放app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}"); });
致电app.UseStaticFiles(); and app.UseRazorComponents<App.Startup>();
在我看来,服务器正在发送index.html而不是(StaticFileMiddleware)
答案 1 :(得分:0)
以防万一有人遇到相同的问题,在我的情况下,这也有效:
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute(); // <- this
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/index_sse");
});