63 lines
2.0 KiB
C#
63 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net.Http;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace SessionZeroClient.API;
|
|
|
|
public class ApiHandler : IApiHandler
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
|
|
public ApiHandler()
|
|
{
|
|
_httpClient = new HttpClient();
|
|
}
|
|
|
|
public async Task<string> Register(string url, string username, string email, string password)
|
|
{
|
|
var apiString = $"{url}/api/Auth/register";
|
|
var requestBody = new Dictionary<string, string>
|
|
{
|
|
{"username", username},
|
|
{"email", email},
|
|
{"password", password}
|
|
};
|
|
|
|
var jsonBody = JsonSerializer.Serialize(requestBody);
|
|
var content = new StringContent(jsonBody, System.Text.Encoding.UTF8, "application/json");
|
|
var response = await _httpClient.PostAsync(apiString, content);
|
|
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
throw new HttpRequestException($"Register failed: {response.StatusCode}");
|
|
|
|
}
|
|
|
|
var responseString = await response.Content.ReadAsStringAsync();
|
|
return responseString;
|
|
}
|
|
|
|
public async Task<string> Login(string url, string username, string password)
|
|
{
|
|
var apiString = $"{url}/api/Auth/login";
|
|
var requestBody = new Dictionary<string, string>
|
|
{
|
|
{"username", username},
|
|
{"password", password}
|
|
};
|
|
|
|
var jsonBody = JsonSerializer.Serialize(requestBody);
|
|
var content = new StringContent(jsonBody, System.Text.Encoding.UTF8, "application/json");
|
|
var response = await _httpClient.PostAsync(apiString, content);
|
|
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
throw new HttpRequestException($"Login failed: {response.StatusCode}");
|
|
}
|
|
|
|
var responseString = await response.Content.ReadAsStringAsync();
|
|
return responseString;
|
|
}
|
|
} |