Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created Nov 3, 2021
Embed
What would you like to do?
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