Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created November 3, 2021 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/9c99f11393f9d295d0dd0c409f5c55ae to your computer and use it in GitHub Desktop.
Save dcomartin/9c99f11393f9d295d0dd0c409f5c55ae to your computer and use it in GitHub Desktop.
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class ProblemDetailsHttpMessageHandler : DelegatingHandler
{
public ProblemDetailsHttpMessageHandler() : base(new HttpClientHandler()) { }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
var response = await base.SendAsync(request, ct);
var mediaType = response.Content.Headers.ContentType?.MediaType;
if (mediaType != null && mediaType.Equals("application/problem+json", StringComparison.InvariantCultureIgnoreCase))
{
var problemDetails = await response.Content.ReadFromJsonAsync<ProblemDetails>(null, ct) ?? new ProblemDetails();
throw new ProblemDetailsException(problemDetails, response);
}
return response;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment