Konvertieren des Inhalts von HttpResponseMessage in ein Objekt

Konvertieren des Inhalts von HttpResponseMessage in ein Objekt

Hier ist ein Beispiel dafür, wie ich es mit MVC API 2 als Backend gemacht habe. Mein Backend gibt ein JSON-Ergebnis zurück, wenn die Anmeldeinformationen korrekt sind. UserCredentials class ist genau das gleiche Modell wie das json-Ergebnis. Sie müssen System.Net.Http.Formatting verwenden die im Microsoft.AspNet.WebApi.Client zu finden sind NugetPackage

public static async Task<UserCredentials> Login(string username, string password)
{
    string baseAddress = "127.0.0.1/";
    HttpClient client = new HttpClient();

    var authorizationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes("xyz:secretKey"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorizationHeader);



    var form = new Dictionary<string, string>
    {
        { "grant_type", "password" },
        { "username", username },
        { "password", password },
    };

    var Response = await client.PostAsync(baseAddress + "oauth/token", new FormUrlEncodedContent(form));
    if (Response.StatusCode == HttpStatusCode.OK)
    {
        return await Response.Content.ReadAsAsync<UserCredentials>(new[] { new JsonMediaTypeFormatter() });
    }
    else
    {
        return null;
    }
}

und Sie brauchen auch Newtonsoft.Json Paket.

public class UserCredentials
    {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }

        [JsonProperty("token_type")]
        public string TokenType { get; set; }

        [JsonProperty("expires_in")]
        public int ExpiresIn { get; set; }

        //more properties...
    }