如何在服务器端应用程序中获取本地数据源? [英] How to get local data source in server side applications?

查看:180
本文介绍了如何在服务器端应用程序中获取本地数据源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用blazor服务器端应用程序.在那我需要引用本地数据源.

I am using blazor server side application. In that I need to refer local dataSource.

我已将Http用作默认客户端示例.

I have used the Http as like default client side sample.

@code{

    ChartData[] dataSource;
    protected override async Task OnInitAsync()
    {
        dataSource = await Http.GetJsonAsync<ChartData[]>("scripts/aapl.json");
    }
}

但是我一直在面对如下问题,

But I have been facing the issue like below,

有人可以指导我解决此问题吗?

Can anyone guide me to fix this?

推荐答案

与客户端Blazor不同,服务器端Blazor要求您将HttpClient添加到DI容器中,并将其注入到组件中.

Unlike client-side Blazor, server-side Blazor requires you to add HttpClient to the DI Container, and inject it into your components.

您可以执行以下操作:

  • 将此代码添加到您的Startup.ConfigureServices方法中:
    // Server Side Blazor doesn't register HttpClient by default
    if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
    {
        // Setup HttpClient for server side in a client side compatible fashion
        services.AddScoped<HttpClient>(s =>
        {
            var uriHelper = s.GetRequiredService<IUriHelper>();
            return new HttpClient
            {
                BaseAddress = new Uri(uriHelper.GetBaseUri())
            };
        });
    }

  • 您还可以使用IHttpClientFactory来配置和创建HttpClient实例(最好)
  • 回答您的问题

    如何在服务器端应用程序中获取本地数据源:

    How to get local data source in server side applications:

    定义可以直接访问数据库的本地服务可以解决问题.请参阅默认的服务器端模板.您可以在服务中使用Entity Framework Core来访问数据库对象.

    Defining a local service that can access the database directly can do the trick. See the default server-side templates how to do that. You may use Entity Framework Core in the service to access the database objects.

    请注意,如果决定切换到Blazor客户端,则使用直接访问数据库的本地服务可能会产生不利影响,因为无法在客户端Blazor上执行的数据访问服务与服务器之间进行通信.这是计划如何实施Blazor应用程序重要性的示例.就个人而言,我会坚持使用HttpClient,并避免使用服务,但这是我的个人观点.其他人可能会不同意.

    Note that using a local service that access your database directly may have unfavorable effects if you decide to switch to Blazor client-side, as communication between your data access service executing on client-side Blazor and your server is not possible. This is an example of the importance of planning how to implement your Blazor app. Personally, I'd stick to HttpClient, and avoid services, but this is my personal view. Others may think otherwise.

    希望这对您有帮助...

    Hope this helps...

    这篇关于如何在服务器端应用程序中获取本地数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆