是否有使用CefSharp从JavaScript调用C#的更轻松的方法?

时间:2019-05-17 12:56:46

标签: .net cefsharp

我将CefSharp用作.Net桌面应用程序的UI,但这部分让我有些头疼,例如使用以下功能:

这是我期望要做的事情:

public Sales ProcessSale(Sales sale) {
    sale.Shift = terminal.CurrentShift;
    sale.SalesPerson = terminal.CurrentUser;

    var errors = sale.ValidateInput();

    if (errors.Count > 0) {
        throw new BusinessValidationException(errors);
    }

    terminal.CreateIdentity(sale);
    worker.FireAndForget(() => {
        SafeStorage.Put(sale);
    });
    return sale;
}

然后在JS端:

try {
    let processedSale = await window['sales'].ProcessSale(this.saleModel);
    // ... call print receipt and carry on
} catch(err) {
    this.modalsService.alert(err.Message);
}

干净整洁;

但是,它不起作用。 CefSharp将对象参数作为ExpandoObjects传递,并且在javascript中引发的错误是C#异常的完整堆栈跟踪打印,这两种处理方式都很糟糕。

这是有效的方法,我讨厌必须这样做:

public string ProcessSale(string sale) {
    try {
        return JsonConvert.SerializeObject(
            ProcessSale(
                JsonConvert.DerializeObject<Sales>(sale)
            )
        );
    } catch(Exception x) {
        return JsonConvert.SerializeObject(x);
    }
}

public Sales ProcessSale(Sales sale) {
    sale.Shift = terminal.CurrentShift;
    sale.SalesPerson = terminal.CurrentUser;

    var errors = sale.ValidateInput();

    if (errors.Count > 0) {
        throw new BusinessValidationException(errors);
    }

    terminal.CreateIdentity(sale);
    worker.FireAndForget(() => {
        SafeStorage.Put(sale);
    });
    return sale;
}

然后:

async otherwiseUnnecessaryProcessSaleWrapper(saleModel) {
    const modelJson = JSON.stringify(saleModel);
    const retvJson = await window['sales'].ProcessSale(modelJson);
    const retv = JSON.parse(retvJson);
    if(retv.ClassName || retv.StackTrace) {
        throw retv;
    } else {
        return retv;
    }
}
. . .
// and only then:
try {
    let processedSale = await otherwiseUnnecessaryProcessSaleWrapper(this.saleModel);
    // ... call print receipt and carry on
} catch(err) {
    this.modalsService.alert(err.Message);
}

有没有办法避免这种不必要的冗长冗长,创建自定义javascript互操作处理程序之类的东西,

0 个答案:

没有答案