Skip to content

Instantly share code, notes, and snippets.

@albertklik
Last active March 31, 2024 02:04
Show Gist options
  • Save albertklik/5f51c4fa2a8cb1aaee01d9f12be290bc to your computer and use it in GitHub Desktop.
Save albertklik/5f51c4fa2a8cb1aaee01d9f12be290bc to your computer and use it in GitHub Desktop.
Http request builder for .net
#nullable enable
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
namespace App.Http;
public class HttpRequest
{
private readonly HttpClient _client = new();
private readonly JsonSerializerOptions _serializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
public string Url { get; set; } = string.Empty;
public MethodType Method { get; set; } = MethodType.Get;
public string BearerToken { get; set; } = string.Empty;
public string Accept { get; set; } = "application/json";
public HttpResponseMessage ResponseMessage { get; set; } = new HttpResponseMessage();
public IDictionary<string, string> Headers { get; } = new Dictionary<string, string>();
public IDictionary<string, string> PathParams { get; } = new Dictionary<string, string>();
public IDictionary<string, string> QueryParams { get; } = new Dictionary<string, string>();
public enum MethodType
{
Get,
Post,
Put,
Delete
}
private void SetHeaders()
{
_client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(Accept));
if (!string.IsNullOrEmpty(BearerToken))
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", BearerToken);
foreach (var (key, value) in Headers)
{
_client.DefaultRequestHeaders.Add(key,value);
}
}
private async Task SetParameters()
{
foreach (var (key, value) in PathParams)
{
Url = Url.Replace($"{{{key}}}", value);
}
Url += "?";
Url += await new FormUrlEncodedContent(QueryParams).ReadAsStringAsync();
}
public HttpRequest()
{
}
public HttpRequest(string url, MethodType method)
{
Url = url;
Method = method;
}
public async Task<T> PerformRequest<T>(object? body = null)
{
SetHeaders();
await SetParameters();
var content = string.Empty;
if (body != null)
{
using StringContent jsonContent = new(
JsonSerializer.Serialize(body),
Encoding.UTF8,
"application/json");
}
ResponseMessage = Method switch
{
MethodType.Get => await _client.GetAsync(Url),
MethodType.Post => await _client.PostAsJsonAsync(Url, body),
MethodType.Put => await _client.PutAsJsonAsync(Url, body),
MethodType.Delete => await _client.DeleteAsync(Url),
_ => throw new ArgumentException("Method Type not Selected")
};
try
{
ResponseMessage.EnsureSuccessStatusCode();
}
catch (Exception e)
{
var json = await ResponseMessage.Content.ReadAsStringAsync();
if (ResponseMessage.StatusCode is HttpStatusCode.InternalServerError or HttpStatusCode.BadRequest)
{
var response = JsonSerializer.Deserialize<ApiErrorResponse>(json) ?? new ApiErrorResponse();
throw new HttpRequestException(response.Title + response.Errors);
}
if (ResponseMessage.StatusCode is HttpStatusCode.UnprocessableEntity)
{
var response = JsonSerializer.Deserialize<ApiResponse<Object>>(json) ?? new ApiResponse<Object>();
throw new HttpRequestException(response.Message);
}
throw new HttpRequestException(e.Message);
}
var jsonResponse = await ResponseMessage.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(jsonResponse) ?? throw new ArgumentException("Erro ao obter dados");
}
}
using System.Net;
namespace App.Http;
public class HttpRequestBuilder: IHttpRequestBuilder
{
private readonly HttpRequest _httpRequest = new();
public IHttpRequestBuilder WithUrl(string url)
{
_httpRequest.Url = url;
return this;
}
public IHttpRequestBuilder WithToken(string token)
{
_httpRequest.BearerToken = token;
return this;
}
public IHttpRequestBuilder WithMethod(HttpRequest.MethodType method)
{
_httpRequest.Method = method;
return this;
}
public IHttpRequestBuilder WithPathParam(string name, string value)
{
_httpRequest.PathParams[name] = value;
return this;
}
public IHttpRequestBuilder WithQueryParam(string name, string value)
{
_httpRequest.QueryParams[name] = value;
return this;
}
public IHttpRequestBuilder Accepts(string accept)
{
_httpRequest.Accept = accept;
return this;
}
public IHttpRequestBuilder WithContentType(string contentType)
{
_httpRequest.Headers["Content-Type"] = contentType;
return this;
}
public IHttpRequestBuilder WithCookies(CookieContainer container)
{
throw new NotImplementedException();
}
public IHttpRequestBuilder AllowAutoRedirect(bool allow)
{
throw new NotImplementedException();
}
public IHttpRequestBuilder WithReferer(string referer)
{
throw new NotImplementedException();
}
public IHttpRequestBuilder WithCustomHeader(string name, string value)
{
_httpRequest.Headers[name] = value;
return this;
}
public HttpRequest Build()
{
return _httpRequest;
}
}
using System.Net;
namespace App.Http;
public interface IHttpRequestBuilder
{
IHttpRequestBuilder WithUrl(string url);
IHttpRequestBuilder WithToken(string token);
IHttpRequestBuilder WithMethod(HttpRequest.MethodType method);
IHttpRequestBuilder WithPathParam(string name, string value);
IHttpRequestBuilder WithQueryParam(string name, string value);
IHttpRequestBuilder Accepts(string accept);
IHttpRequestBuilder WithContentType(string contentType);
IHttpRequestBuilder WithCookies(CookieContainer container);
IHttpRequestBuilder AllowAutoRedirect(bool allow);
IHttpRequestBuilder WithReferer(string referer);
IHttpRequestBuilder WithCustomHeader(string name, string value);
HttpRequest Build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment