Solarion
Honorary Master
- Joined
- Nov 14, 2012
- Messages
- 28,050
- Reaction score
- 17,803
Hi guys. Please can you guys advise me on something. I have a login page going for my MVC however this "async Task" is actually messing with the way the controller is operating.
Please help me to refactor this so that I can still run these await methods but without the Controller returning an async task. The Login itself is working and returns a token. However having this function in a task is messing with the way the login page redirects to the Home controller. Please assist
This is the method behing PostAsync
Please help me to refactor this so that I can still run these await methods but without the Controller returning an async task. The Login itself is working and returns a token. However having this function in a task is messing with the way the login page redirects to the Home controller. Please assist
C#:
public async Task<bool> LoginUserAsync(string url, string userName, string password)
{
try
{
TokenRequest Token;
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "email", "[email protected]" },
{ "password", "Admin123" }
};
var content = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
var responseString = await response.Content.ReadAsStringAsync();
Token = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenRequest>(responseString);
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Token.token);
}
catch(Exception ex)
{
throw ex;
}
return true;
}
This is the method behing PostAsync
C#:
public async Task<T> PostAsync<T>(string methodUrl, object model)
{
HttpClient client = new HttpClient();
// Now serialzize the object to json
string jsonData = JsonConvert.SerializeObject(model);
// Create a content
HttpContent content = new StringContent(jsonData);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
// Make a request
var response = await client.PostAsync(methodUrl, content);
var responseAsString = await response.Content.ReadAsStringAsync();
// Deserialize the coming object into a T object
T obj = JsonConvert.DeserializeObject<T>(responseAsString);
return obj;
}


