【问题标题】:Server side blazor app httpclient calls are not reaching my web API controller class服务器端 Blazor 应用程序 httpclient 调用未到达我的 Web API 控制器类
【发布时间】:2019-02-09 20:48:56
【问题描述】:

我正在尝试在 .Net Core 3.0 预览版中使用 Blazor 服务器端应用程序 (RazorComponents) 创建多人游戏。我的服务器项目中有一个 SQL lite 数据库和数据访问层来存储游戏信息。我有一个控制器类,也在服务器项目中,使用数据访问层从数据库返回对象。我在 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'。物理路径:'{path to my game}.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

【问题讨论】:

  • 我在使用 .net 5 时也遇到了同样的问题...我确实检查了所有控制器路由,但它们都自动转到 404,客户端正在响应。我尝试验证,一切正常...我还创建了一个新项目并比较了配置,没有什么不同...

标签: c# asp.net-core-webapi blazor blazor-server-side


【解决方案1】:

试试这个:把app.UseMvc(routes =&gt; { routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}"); }); 在打电话之前app.UseStaticFiles(); and app.UseRazorComponents&lt;App.Startup&gt;();

在我看来,服务器正在发送 index.html (StaticFileMiddleware)

【讨论】:

  • 成功了!谢谢!我从来没有意识到配置方法中的顺序很重要
  • 您是如何让 HttpClient 与 Blazor Server 一起工作的? HttpClient 是 WebAssembly 的客户端。
【解决方案2】:

以防万一有人遇到同样的问题,在我的情况下这也有效:

app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute(); // <- this
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/index_sse");
});

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2020-09-18
    • 2021-10-21
    • 2021-12-29
    相关资源
    最近更新 更多