mirror of
https://github.com/Sarsoo/IF.Lastfm.git
synced 2024-10-17 07:13:09 +01:00
b249ea7fa8
Using this mean clients don't have to wrap every call in try/catches http://stackoverflow.com/questions/18562613/async-method-returning-taskt-with-generic-constraint-in-c-sharp?noredirect=1#comment27311729_18562613
55 lines
1.5 KiB
C#
55 lines
1.5 KiB
C#
using System;
|
|
using System.Net.Http;
|
|
using System.Threading.Tasks;
|
|
using IF.Lastfm.Core.Api.Enums;
|
|
using IF.Lastfm.Core.Api.Helpers;
|
|
|
|
namespace IF.Lastfm.Core.Api.Commands
|
|
{
|
|
internal abstract class PostAsyncCommandBase<T> : LastAsyncCommandBase<T> where T : LastResponse, new()
|
|
{
|
|
protected PostAsyncCommandBase(IAuth auth)
|
|
{
|
|
Auth = auth;
|
|
}
|
|
|
|
protected override Uri BuildRequestUrl()
|
|
{
|
|
return new Uri(LastFm.ApiRoot, UriKind.Absolute);
|
|
}
|
|
|
|
public override async Task<T> ExecuteAsync()
|
|
{
|
|
SetParameters();
|
|
|
|
Url = BuildRequestUrl();
|
|
|
|
Parameters.Add("sk", Auth.User.Token);
|
|
|
|
var apisig = Auth.GenerateMethodSignature(Method, Parameters);
|
|
|
|
var postContent = LastFm.CreatePostBody(Method,
|
|
Auth.ApiKey,
|
|
apisig,
|
|
Parameters);
|
|
|
|
try
|
|
{
|
|
var httpClient = new HttpClient();
|
|
var response = await httpClient.PostAsync(Url, postContent);
|
|
return await HandleResponse(response);
|
|
}
|
|
catch (HttpRequestException)
|
|
{
|
|
if (LastFm.CatchRequestExceptions)
|
|
{
|
|
return LastResponse.CreateErrorResponse<T>(LastFmApiError.RequestFailed);
|
|
}
|
|
else
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |