C# 无法通过 HttpResponseMessage 获取 HTTP Return 代码

C# Unable to Get HTTP Return Codes via HttpResponseMessage

我在尝试通过 API.
检查构建方法的 Return 代码和 post 数据时遇到错误 产生错误的行是:

if (BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4) == MyGlobals.ReturnCode)

错误是:
运算符 '==' 不能应用于 'Task<string'>' 和 'string'

类型的操作数 我的目标是将这些参数(data1、data5 等)传递给 BuildApi() 方法,然后通过 API 调用 post 该数据。

当数据成功 posted 时,如果发生错误,我应该得到 Return 代码 200 或 Return 代码 400(根据 API 开发人员)。

BuildApi() 方法应该 return 返回条件语句的 200 或 400。

BuildApi() 方法的格式是否正确 return Return 代码?如果是,“if”语句有什么问题?

在此先感谢您的帮助!

完整代码:

static class MyGlobals
{
    public static XmlDocument XmlAccounts = new XmlDocument();
    public static XmlNode XmlRoot;
    public static string data1 { get; set; }
    public static string data2 { get; set; }
    public static string data3 { get; set; }
    public static string data4 { get; set; }
    public static string data5 { get; set; }
    public static string ReturnCode { get; set; }

}

static HttpClient client = new HttpClient();
static void Main(string[] args)
{
    SqlConnection ObjConn = new SqlConnection();
    string ConnectMe = @"

            Data Source             =SERVER;
            Database                =DATABASE1;
            User ID                 =USER;
            Pwd                     =PASS;
            Connection Timeout      =700

        ";



    // Open Connection
    ObjConn = new SqlConnection(ConnectMe);
    ObjConn.Open();

    // Call methods based on the required tool
    SR_Provisioning(ObjConn);
    
}

static public void SR_Provisioning(SqlConnection ObjConn)
{
    Get = @"

        SELECT
            data1,
            data2,
            data3,
            data4,
            data5

        FROM
            table
    ";



    ObjAdp = new SqlDataAdapter(Get, ObjConn);
    ObjAdp.Fill(OutputTable); 

    foreach (DataRow OutputRow in OutputTable.Rows)

    {

        //Initalize FQAN

        string FQAN = "";



        // Convert query output to variables

        MyGlobals.data1 = OutputRow[0].ToString();
        MyGlobals.data2 = OutputRow[1].ToString();
        MyGlobals.data3 = OutputRow[2].ToString();
        MyGlobals.data4 = OutputRow[3].ToString();
        MyGlobals.data5 = OutputRow[4].ToString();

        // Instantiate new objects

        strFunctions MyStr = new strFunctions();
        wshWin32API win32api = new wshWin32API();

        // Convert server to FQDN for accessibility ease
        string FQDN = getFQDN(MyGlobals.data1, ObjConn);

        // Perform action based on Tranaction_Type
        switch (MyGlobals.data5)

        {
            case "Add":
                if (MyGlobals.data2 == "LOCAL")
                {
                    // Create local ID first
                    try
                    {
                        FQAN = MyGlobals.data1 + "\" + MyGlobals.data3;
                        // Check the return code to determine how to log the results

                        if (BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4) == MyGlobals.ReturnCode)

                        {
                            switch (MyGlobals.ReturnCode)
                            /*
                                Return Codes
                                200 (Created)
                                400(Expectation Failed)
                            */

                            {
                                case "200":
                                    // Do something
                                    AllIsGood();
                                    break;

                                case "400":
                                    // Do something else
                                    AllIsBad();
                                    break;
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        // Handle error and update transaction record
                        Update_Row();
                    }
                }
}


static async Task<string> BuildApi(string data5, string data1, string FQAN, string data4)

{
    try
    {
        UriBuilder baseUri = new UriBuilder("https://pwmfunction001.azurewebsites.net/api/VMGroupMemberModify01?code=T753ljF4jwXZXzmotCnnrBdV7Mrbqvcd3ibazRb92ZoBfJADuCpq5w==-Headers@{Metadata=true}-Body@{");

        // Create the query string
        string queryToAppend = "DATA5=" + data5 + ";DATA1=" + data1 + ";FQAN=" + FQAN + ";data4=" + data4 + "}";

        if (baseUri.Query != null && baseUri.Query.Length > 1)
        {
            baseUri.Query = baseUri.Query.Substring(1) + ";" + queryToAppend;
        }
        else
        {
            // Check this
            baseUri.Query = queryToAppend;
        }

        string httpResponseBody = "";
        
        var client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        
        var content = new StringContent(client.ToString());
        HttpResponseMessage response = await client.PostAsync(baseUri.ToString(), content);

        if (response.IsSuccessStatusCode)
        {
            httpResponseBody = "200";
            return httpResponseBody;
        }
        else
        {
            httpResponseBody = "400";
            return httpResponseBody;
        }
    }
    catch(HttpRequestException err)
    {
        throw err;
    }  

}
}

}

您的 BuildApi 函数是异步的,因此您需要在代码中等待它:

if (await BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4) == MyGlobals.ReturnCode)

更新:

如果你不能运行它异步那么你需要结果:

if (BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4).Result == MyGlobals.ReturnCode)

但是,我会首先尝试让您的调用方法异步