@manhnguyenv

Welcome to my blog!

Create New Asp.net Identity User using HttpClient from WinForms

November 10, 2017 09:18

Configure HttpClient

private static HttpClient httpClient = new HttpClient
{
BaseAddress = new Uri(ConfigManager.ConfigurationInstant.ApiBaseAuthUri)
};

private static HttpClient client = new HttpClient
{
BaseAddress = new Uri(ConfigManager.ConfigurationInstant.ApiBaseUri)
};

Create new user

private static async Task<ApiAsyncResult> CreateNewUser(string userName, string password, string confirmPassword)
{
var result = new ApiAsyncResult();

httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

try
{
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("email", userName),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("confirmPassword", confirmPassword)
});

using (HttpResponseMessage response = await httpClient.PostAsync("/Account/Register", formContent))
{
using (HttpContent content = response.Content)
{
string resultString = await content.ReadAsStringAsync();
string reasonPhrase = response.ReasonPhrase;
HttpResponseHeaders headers = response.Headers;
HttpStatusCode code = response.StatusCode;

result.Result = resultString;
result.ReasonPhrase = reasonPhrase;
result.Headers = headers;
result.Code = code;
}
}
}
catch (Exception ex)
{
result.ErrorMessage = ex.Message;
}

return result;
}

ApiAsyncResult.cs

public class ApiAsyncResult
{
public string Result { get; set; }
public string ReasonPhrase { get; set; }
public HttpResponseHeaders Headers { get; set; }
public HttpStatusCode Code { get; set; }
public string ErrorMessage { get; set; }
}

Categories

Recent posts