2

To give some context, I'm trying to connect an existing C# application with a React SPA. The problem is, that the C# code includes some really difficult mathematical calculations and I can't rewrite it.

My idea was to build a Blazor WebAssembly application, which includes the existing code base.

After countless hours of trying several different solutions, I figured out, that it's possible to copy the Blazor "_framework" folder (generated by building the project) into my React public folder. This allowed my to call static C# methods from my JavaScript code. All good so far, but unfortunately it's not possible to call non-static methods.

According to this article it should be possible to send the C# instance via IJSRuntime, but this isn't working for my case. From my perspective it looks like the IJSRuntime doesn't get injected because the JavaScript code is not part of Blazor.

Does anyone know any solution how to inject the IJSRuntime with the React environment? Or is there any better solution to call C# code from a React application?

1 Answer 1

1

Instead of going through all of this stuff, why not just use a simple REST API? You can simply implement an endpoint that accepts the parameters (via HTTP) and returns the result. In most cases, this is far easier to setup and maintain than other possible approaches.

Simply add:

app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

Then just create your controller, which accepts your non-static services in the constructor (via dependency injection) that do the math, and return the values:

[ApiController]
class MathController : ControllerBase
{
  private readonly MyCalculatorService calculator;

  MathController(MyCalculatorService calculator) {
    this.calculator = calculator;
  }

  [HttpPost("api/math/my-math")]
  public async Task<ActionResult<MathResult>> MyMathEndpoint([FromBody] MathInput mathInput) {
    var result = calculator.GetResult(mathInput);

    return new JsonResult(result);
  }
}

MathInput and MathResult are just examples, but you can really use just about anything.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.