Benutzerdefinierte Ausnahmebehandler im API -Controller, der in C# und .NET 8 fehlschlägtC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Benutzerdefinierte Ausnahmebehandler im API -Controller, der in C# und .NET 8 fehlschlägt

Post by Anonymous »

Ich lerne derzeit über Fehlerfehlermanagement in ASP.NET -Web -API -Projekten, um zu versuchen, eine elegante Lösung zu finden, die sicherstellt /> Ich verwende die Standard -WeatherforeCast < /code> -API implementierte einen benutzerdefinierten Ausnahmebehandler; Ich stelle jedoch fest, dass es nicht immer funktioniert. , Statuscode und Headerinformationen; Wenn ich jedoch die API von der Funktion "Try It" in der Swagger -Schinnee übernehme, werde ich mit Ausnahmedetails anstelle eines Problemdetails und des falschen Header -Informationen. /Code> Methode gibt false zurück, wenn ich den Code von Swagger probiere; Wenn ich jedoch genau den gleichen Code ausführe, indem ich ihn vom Postanbau aufruft. Denn wenn der 'problemDetailsService.trywriteEasync (...)' zurückgibt, kann ich versuchen, das ProblemDetailsContext direkt in die httpcontext.response zu schreiben.
Als ich dies tat, konnte ich die folgende Ausnahme aufnehmen (dies geschieht erneut, wenn ich Swaggers Versuchscodefunktion verwendete ... nicht beim Aufrufen von Postman): < /p>

< P> Serialisierung und Deserialisierung von 'System.Type' Instances wird nicht unterstützt. Pfad: $ .httpcontext.Features.key. "< /P>
< /Blockquote>
Ich weiß nicht, warum dies fehlschlägt. < /P>
Ich suche Hilfe, um sicherzustellen, wie ich sicherstellen kann, dass sich mein Fehlermanagement auf die gleiche Weise verhält, unabhängig davon, wie die API aufgerufen wird. /p>

Code: Select all

public class GlobalExceptionHandler : IExceptionHandler
{
private readonly IProblemDetailsService _problemDetailsService;

public GlobalExceptionHandler(IProblemDetailsService problemDetailsService)
{
if (problemDetailsService == null) throw new ArgumentException(nameof(problemDetailsService));
_problemDetailsService = problemDetailsService;
}

public async ValueTask TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
var message = exception switch
{
ArgumentException => ((ArgumentException)exception).Message,
ValidationException => ((ValidationException)exception).Message,
_ => $"Internal Server Error ({exception.GetType().Name})"
};

int status = exception switch
{
ArgumentException => (int)HttpStatusCode.BadRequest,
ValidationException => (int)HttpStatusCode.BadRequest,
_ => (int)HttpStatusCode.InternalServerError
};

ProblemDetails problemDetails = new()
{
Title = $"Bad Request: {exception.GetType().Name}", // human-readable summary of the [url=viewtopic.php?t=11587]problem[/url] type
Detail = message, //detailed explanation specific to the problem
Status = status,
Instance = httpContext.Request.GetEncodedUrl(),
Type = exception.HelpLink
};

var errorcontext = new ProblemDetailsContext()
{
HttpContext = httpContext,
ProblemDetails = problemDetails,
//Exception = exception,
AdditionalMetadata = null
};

httpContext.Response.Clear();
httpContext.Response.StatusCode = status;

var written = await _problemDetailsService.TryWriteAsync(errorcontext);

if (!written)
{
try
{
await httpContext.Response.WriteAsJsonAsync(errorcontext);
written = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
written = false;
}
}

return written;
}
}
Dies ist mein Programm.cs :

Code: Select all

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Net.Http;
using Microsoft.AspNetCore.Diagnostics;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Add services to the container.
builder.Services.AddExceptionHandler
();   // Using a custom exception handler that converts the exception into a [url=viewtopic.php?t=11587]Problem[/url] Details
builder.Services.AddProblemDetails();  // required for using the exception handler with the custom [url=viewtopic.php?t=11587]problem[/url] details exception handler code because it adds the services required for [url=viewtopic.php?t=11587]Problem[/url] Details

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseExceptionHandler(opt => { }); //adding the custom GlobalExceptionHandler to the app's pipeline
app.UseAuthorization();

app.MapControllers();

app.Run();
Und dies ist die Implementierung für meinen WeatherforeCastController (nicht, dass das Aufrufen des Posts oder Get die Ausnahme vom benutzerdefinierten Ausnahmebehandler ausgelöst wird)
< Br />

Code: Select all

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{

private readonly ILogger _logger;

public WeatherForecastController(ILogger  logger)
{
_logger = logger;
}

[HttpGet("GetWeatherForecast")]
public ActionResult GetWeatherForecast()
{

throw new ArgumentException("Please provide a valid value for a week day: between 0 and 6");

}

[HttpPost("PostWeatherForecastDTO")]
public ActionResult PostWeatherForecastDTO()
{
throw new Exception("Please provide a valid value for a week day: between 0 and 6");

}
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post