【问题标题】:Static method invocation using JSInterop/Blazor使用 JSInterop/Blazor 的静态方法调用
【发布时间】:2020-03-31 15:26:09
【问题描述】:

(#)首发

我正在使用 JSInterop 和 Blazor/RazorPages 在单击表上的项目时调用方法。互操作规范只允许使用静态方法。好吧,从技术上讲,也可以使用实例方法,但其文档确实令人困惑。我几乎可以肯定,如果没有 Blazor '@onclick' tag-helper,实例方法调用将无法工作——我无法在本示例中使用它。

这是有效的:

public class Dashboard : PageModel

private readonly DeviceService _deviceService;
public Dashboard (DeviceService deviceService)
{
     _deviceService = deviceService;
}

//I want to use the above instance of deviceService, for a JSInvokable method

[JSInvokable]
public static async Task<List<string>> DeviceDetails(string deviceName)
{
    List < string > details = new List<string>();
    Uri location = new Uri("http://superapi.com/api/devices");
    HttpClient client = new HttpClient();
    client.BaseAddress = location;

    DeviceService dev = new DeviceService(client);

    Device details = await dev.GetDeviceByName(deviceName);

    return details;
}
//This <script> is what the client gets in their browser when they visit the page.
function () {
            var table = $('#<TableName>').DataTable();
            var d = table.row(this).data();
            DotNet.invokeMethodAsync("<namespace>", "DeviceDetails", d[0])
                .then(data => {
                    document.getElementById("Property1").innerHTML = data[0];
                    document.getElementById("Property2").innerHTML = data[1];
                    document.getElementById("Property3").innerHTML = data[2];
                    document.getElementById("Property4").innerHTML = data[3];
                    document.getElementById("Property5").innerHTML = data[4];
                });
        });

invokeMethodAsync 的 MS 文档声明它仅适用于静态方法,这些方法不允许我访问我在 PageModel 中声明的 DeviceService 实例。它迫使我用“新”的一切创建一个相当丑陋的新实例。

我认为解决方案可能涉及使用接口或依赖注入,有人有建议吗?

【问题讨论】:

  • 这是对您问题的回答吗? stackoverflow.com/questions/59134029/…
  • @agua from mars 不是真的,我不是从 .razor 页面调用。这是一个常规的 .cshtml
  • 贴出代码,没有上下文我们帮不了你
  • 我已经添加了调用 JSInvokable 方法的 JS 脚本。这是在使用 blazor 服务器的 .cshtml 页面上。让我知道这是否是您在“上下文”方面正在寻找的内容。
  • 我的意思是,在所有上下文中,我们无法猜测它是从 blazor 应用程序外部的 cshtml 调用的,这是您尝试做的吗?

标签: javascript c# razor static-methods blazor


【解决方案1】:

我通过研究依赖注入发现了一个答案。我使用以下方法从我的 appsetting.json 注册了一个字符串:

IConfigurationSection baseAPI = Configuration.GetSection("BaseAddress");
services.Configure<ApiBaseAddress>(baseAPI);

然后在我注入的页面上:

@inject IOptions<ApiBaseAddress> BaseAddress

现在我们可以在参数中将此 BaseAddress 发送给静态方法:

DotNet.invokeMethodAsync("<namespace>", "DeviceDetails", d[0], "@BaseAddress.Value.Uri")

这允许我们在 URI 创建期间访问:

Uri location = new Uri(baseUri + "/api/worker");

虽然这并不完美 - 我真的不想从头开始创建服务,但至少我不需要在部署期间更改多段代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 2020-06-17
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    • 2013-03-20
    相关资源
    最近更新 更多