'ASP.NET core 5 web api connect exchange via powershell script

In my asp.net core 5 project I want to execute the ps script below. This script can be executed in a native powershell without errors. And I can run simple ps scripts in my project context. But if I run this script via IIS Express (same machine as native powershell) then it thrwos the following error msg:

Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid value for the argument, and then try running the command again.

The msg belongs to the Import-PSSession command. How to run the script in asp.net core project context?

$Username = 'user'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass

$ExchangeFQDN = 'exchange.domain'
$ConnectionURI = "http://$($ExchangeFQDN)/powershell"
try{
    $mSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ConnectionURI -Credential $Cred -Authentication Kerberos
    Import-PSSession $mSession -DisableNameChecking
}catch{
    echo $_
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source