我正在尝试在.NET核心3.0预览版中使用Blazor服务器端应用程序(razocomponents)创建多人游戏。我在服务器项目中有一个SQL Lite数据库和数据访问层来存储游戏信息。我有一个控制器类,也在服务器项目中,使用数据访问层从数据库返回对象。应用程序项目中的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";
}
}
我的服务器。启动文件注册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();
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(s =>
{
// Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
var uriHelper = s.GetRequiredService();
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.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”
所以它似乎没有被正确地路由到控制器。我一直在谷歌搜索别人是如何做到这一点的,似乎我做的是正确的方式。有人知道我错过了什么吗?