簡體   English   中英

無法從Windows應用程序接收來自HTTP Post請求對C#Web API的響應

[英]Unable to receive response from HTTP Post request to C# Web API from Windows Application

我有一個托管在特定域的C#Web API應用程序。
使用郵遞員,所有Web api的工作都可以按預期進行,包括使用它的應用程序。

現在,我有一個場景, 我需要從C#Windows應用程序托管的C#Web API發出POST請求

我已經嘗試過Google(ing)這個問題,但只能找到部分解決方案來解決我的問題。

當我使用Postman調用webapi時; 這是我得到的實際/必需的JSON響應:

{
    "access_token": "7oIHQgUyb4NJc-kAc4Ce7Xa1ly5vKCaoxh0w-3PDixpvZtJkBLy7dg6kyE0gp_EZ_9pmh7LC06ztBKNyLbpLcruV9uHEVvIrvKvt0zowUv3Ho9sDGddvGy808N_tliljM8HYe4wJlcwlE9VzlWEv7bz3CNRNj_o9WLqPjcRTu2LN9wMAyMSXGdI_rE2guw-1w1W6aoDgr71x61InbRJ_DNqNpH0MhIUprhTeEVh59WEaq76FLErHTo3TXUTcjximVlxHQPZWh0gWN3dX7sI_Wz60RUK_h4SZO2VZ3QWZivPXX8CsOlXaullq0MnSLogb",
    "token_type": "bearer",
    "expires_in": 28799,
    "Username": "Gomesdenver",
    "UserId": "490253d0-79f6-4aed-96a9-5a041375d84c",
    "Role": "3b55f063-eb24-4e76-b30d-c2509c37fd8a",
    "DisplayAY": "2019-2020"
}


請參見下面的圖片(郵遞員的回復是我想要的): 對JSON響應感興趣

我的C#Windows代碼如下:

public async Task<string> LoginUser(string Username, string Password, Notifier notification)
{
    string strResult = string.Empty;
    dynamic res;
    HttpClient client = new HttpClient();
    try
    {
        notification("Attempting to contact database. Please wait..");
        await Task.Delay(750);

        var dict = new Dictionary<string, string>();
        dict.Add("username", "GomesDenver");
        dict.Add("password", "MyPassword");
        dict.Add("grant_type", "password");

        client.BaseAddress = new Uri("http://dummyuri.com/");
        client.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "token")
        {
            Content = new FormUrlEncodedContent(dict)
        };

        res = client.SendAsync(request).Result;
    }
    catch (Exception ex)
    {
        strResult = ex.Message.ToString();
    }
    finally
    {
        // Do nothing
    }

    return strResult;
}

一切都按預期進行; 但我無法像郵遞員那樣獲取響應。 我使用此代碼得到的結果是: 收到結果

我收到狀態代碼為“ OK”,但是如何從該請求訪問JSON響應? 如何在C#Windows應用程序代碼中獲取令牌值。

提前致謝。

利用HttpResponseMessage類

        HttpResponseMessage httpResponseMessage = await client.SendAsync(request);
        string response = await httpResponseMessage.Content.ReadAsStringAsync();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM