How to I make a cURL command call from .Net Core 3.1 Code

爱⌒轻易说出口 提交于 2021-01-29 14:44:07

问题


I have this complicated cURL command that is working perfectly:

curl -L --negotiate -u : -b ~/cookiejar.txt  "https://idp.domain.net/oauth2/authorize? scope=openid&response_type=code&redirect_uri=https://localhost:5001&client_id=client_id_here"

However it is not really feasible to replicate in C# using HttpClient. But I need to call the cURL command from .Net Core code and get the response back.

Is there a way to make a normal cURL command call in .Net Core (v3.1)?

(In case you are interested, this is the details on the cURL command: Replicate cURL Command Using Redirect and Cookies in .Net Core 3.1)


回答1:


This can be done via an integrated call to powershell.

  1. Install the NuGet Microsoft.Powershell.SDK.
  2. Add the using statement of System.Management.Automation
  3. Add the following method:

-

public List<string> ExecutePowershell(string command)
{
    var resultsAsString = new List<string>();
    using (var ps = PowerShell.Create())
    {
        var results = ps.AddScript(command).Invoke();
        foreach (var result in results)
        {
            resultsAsString.Add(result.ToString());
        }
    }
    return resultsAsString;
}
  1. Call it like this:

-

void Main()
{
    var results = ExecutePowershell("curl -L --negotiate -u : -b ~/cookiejar.txt  /"https://idp.domain.net/oauth2/authorize? scope=openid&response_type=code&redirect_uri=https://localhost:5001&client_id=client_id_here/"");
    Console.WriteLine(results);
}

I drew this from this answer: https://stackoverflow.com/a/47777636/16241



来源:https://stackoverflow.com/questions/60999574/how-to-i-make-a-curl-command-call-from-net-core-3-1-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!