Using Node Services in ASP.NET Core

Programming, error messages and sample code > Node.js
With the Microsoft.AspNetCore.NodeServices package, you can use easily use Node.js in your ASP.NET Core application.
Add the Node Services middleware to the request pipeline. You can do it in your ConfigureServices() method.
       //Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
            services.Configure<CookiePolicyOptions>(options =>
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;

Now you’re able to get instance of INodeServices in your application. INodeServices is the API through which .NET code can make calls into JavaScript that runs in a Node environment. You can use FromServices attribute to get the instance of `INodeServices’ in your action method. Here is Add method implementation in MVC.

        public async Task<IActionResult> Add([FromServices] INodeServices nodeServices)
            var num1 = 10;
            var num2 = 20;
            var result = await nodeServices.InvokeAsync<int>("AddModule.js", num1, num2);
            ViewData["ResultFromNode"] = $"Result of {num1} + {num2} is {result}";
            return View();
And here is the code of AddModule.js file.
module.exports = function(callback, num1, num2) { 
  var result = num1 + num2;
  callback(null, result);