如何在 C# 中创建流

How to create flow in C#

我已参考此 https://docs.microsoft.com/en-us/power-automate/web-api link 以编程方式创建流程,但是当我在我的 C# 代码中使用 Api 时,我收到“未处理的异常。System.Net.WebException: 远程服务器返回错误: (401) Unauthorized.at System.Net.HttpWebRequest.GetResponse()"

static void Main(string[] args)
    {

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://orgxxxxxx.crmx.dynamics.com/api/data/v9.1/workflows");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string str = "{\"properties\":{\"connectionReferences\":{\"shared_commondataservice\":{\"connectionName\":\"shared-commondataser-00000000-0000-0000-0000-000000000004\",\"source\":\"Invoker\",\"id\":\"/providers/Microsoft.Power Apps/apis/shared_commondataservice\"}},\"definition\":{\"$schema\": \"https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#\",\"contentVersion\": \"1.0.0.0\",\"parameters\": {\"$connections\": {\"defaultValue\": {},\"type\": \"Object\"},\"$authentication\": {\"defaultValue\": {},\"type\": \"SecureObject\"}},\"triggers\": {\"Recurrence\": {\"recurrence\": {\"frequency\": \"Minute\",\"interval\": 1},\"type\": \"Recurrence\"}},\"actions\": {\"List_records\": {\"runAfter\": {},\"metadata\": {\"flowSystemMetadata\": {\"swaggerOperationId\": \"GetItems_V2\"}},\"type\": \"ApiConnection\",\"inputs\": {\"host\": {\"api\": {\"runtimeUrl\": \"https://firstrelease-001.azure-apim.net/apim/commondataservice\"},\"connection\": {\"name\": \"@parameters('$connections')['shared_commondataservice']['connectionId']\"}},\"method\": \"get\",\"path\": \"/v2/datasets/@{encodeURIComponent(encodeURIComponent('default.cds'))}/tables/@{encodeURIComponent(encodeURIComponent('accounts'))}/items\",\"queries\": {\"$top\": 1},\"authentication\": \"@parameters('$authentication')\"}}},\"outputs\": {}}},\"schemaVersion\":\"1.0.0.0\"}";
            string json = "{" +
                 "\"category\": 5," +
                 "\"statecode\": 0 "+
                 "\"type\": 1," + 

                 "\"description\": \"This flow reads some data from Dataverse.\"," +
                 "\"primaryentity\":\"none\"," +
                 "\"clientdata\":"+  str +
                 "}";



        streamWriter.Write(json);
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

    }

输出:

Unhandled exception. System.Net.WebException: The remote server returned an error: (401) Unauthorized.at System.Net.HttpWebRequest.GetResponse()

您收到 401 响应,这意味着您没有发送授权 header

这个link会对你有帮助