{"id":810,"date":"2023-02-14T10:18:42","date_gmt":"2023-02-14T10:18:42","guid":{"rendered":"https:\/\/oussamasaidi.com\/?p=810"},"modified":"2025-12-20T11:14:44","modified_gmt":"2025-12-20T11:14:44","slug":"net-6-gestion-des-exceptions-globales-de-lapi-web","status":"publish","type":"post","link":"https:\/\/oussamasaidi.com\/en\/net-6-gestion-des-exceptions-globales-de-lapi-web\/","title":{"rendered":".NET 6 &#8211; Gestion des exceptions globales de l&rsquo;API Web"},"content":{"rendered":"<ul><li><a class=\"aioseo-toc-item\" href=\"#aioseo-conditions-prealables\">Conditions pr\u00e9alables<\/a><\/li><li><a class=\"aioseo-toc-item\" href=\"#aioseo-introduction\">\ufffc Introduction<\/a><\/li><li><a class=\"aioseo-toc-item\" href=\"#aioseo-code\">\ufffcCode<\/a><\/li><li><a class=\"aioseo-toc-item\" href=\"#aioseo-derniers-articles\">Derniers Articles<\/a><\/li><\/ul>\n\n\n<p>Vous pouvez trouver le code source complet sur <a href=\"https:\/\/github.com\/oussama-saidi\/net-api-globalexcpetions\" target=\"_blank\" rel=\"noopener\" title=\"\">github<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"aioseo-conditions-prealables\"><strong>Conditions pr\u00e9alables<\/strong><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Code Visual Studio \/ Visual Studio <\/li>\n\n\n\n<li>SDK .NET Core 6<\/li>\n\n\n\n<li>Compr\u00e9hension de la programmation C#<\/li>\n\n\n\n<li>Compr\u00e9hension des API .NET Core<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"aioseo-introduction\"><a href=\"https:\/\/dev-to.translate.goog\/moe23\/net-6-web-api-global-exceptions-handling-1a46?_x_tr_sl=en&amp;_x_tr_tl=fr&amp;_x_tr_hl=fr&amp;_x_tr_pto=wapp#introduction\"><\/a> <strong>Introduction<\/strong><\/h2>\n\n\n\n<p>Lorsque nous construisons notre application, bien que nous esp\u00e9rons que notre application fonctionnera sans aucune erreur jusqu&rsquo;\u00e0 la fin des temps. Ce n&rsquo;est pas vraiment le cas, des exceptions se produisent dans les applications et nous devons les g\u00e9rer.<\/p>\n\n\n\n<p>La gestion des exceptions est une base que nous devons prendre en compte lors de la conception et de la construction de notre application pour avoir une application stable et \u00e9viter les pannes d&rsquo;application.<\/p>\n\n\n\n<p>Il existe de nombreuses fa\u00e7ons d&rsquo;impl\u00e9menter la gestion des exceptions lors de la construction de nos applications \u00e0 partir d&rsquo;une approche tr\u00e8s granulaire vers une approche plus g\u00e9n\u00e9rique.<\/p>\n\n\n\n<p>Dans cet article, nous explorerons la gestion globale des exceptions via le middleware pour d\u00e9tecter efficacement les erreurs d&rsquo;ex\u00e9cution conform\u00e9ment \u00e0 nos exigences.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"aioseo-code\"><a href=\"https:\/\/dev-to.translate.goog\/moe23\/net-6-web-api-global-exceptions-handling-1a46?_x_tr_sl=en&amp;_x_tr_tl=fr&amp;_x_tr_hl=fr&amp;_x_tr_pto=wapp#code\"><\/a>Code<\/h2>\n\n\n\n<p>La premi\u00e8re chose que nous devons faire est de cr\u00e9er une nouvelle application WebApi<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">dotnet new webapi -n ErrorManagement<\/pre>\n\n\n\n<p>Maintenant que notre application a \u00e9t\u00e9 cr\u00e9\u00e9e, nous devons installer certains packages<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">dotnet add package Microsoft.EntityFrameworkCore \ndotnet add package Microsoft.EntityFrameworkCore.Design \ndotnet add package Npgsql.EntityFrameworkCore.PostgreSQL\ndotnet add package Microsoft.EntityFrameworkCore.Tools<\/pre>\n\n\n\n<p>Pour nous assurer que tout fonctionne comme il se doit, nous devons cr\u00e9er notre application<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">dotnet build<\/pre>\n\n\n\n<p>Il est maintenant temps d&rsquo;ajouter les mod\u00e8les, pour cet exemple d&rsquo;application, nous allons cr\u00e9er une application pour r\u00e9pertorier tous les pilotes F1. Pour cela nous allons cr\u00e9er un dossier Models dans le r\u00e9pertoire racine de notre application qui contiendra nos mod\u00e8les Dans le dossier Models, nous allons cr\u00e9er une nouvelle classe appel\u00e9e Employee<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">namespace Net.WebApi.Globalexcpetions.Models;\n\npublic class Employee\n{\n    public int Id { get; set; }\n    public string FirstName { get; set; } = \"\";\n    public string LastName { get; set; } = \"\";\n}\n<\/pre>\n\n\n\n<p>Une fois le mod\u00e8le cr\u00e9\u00e9, l&rsquo;\u00e9tape suivante consiste \u00e0 cr\u00e9er notre contexte de base de donn\u00e9es dans le r\u00e9pertoire racine de notre application. Nous allons cr\u00e9er un nouveau dossier appel\u00e9 Data et \u00e0 l&rsquo;int\u00e9rieur du dossier Data, nous ajouterons la classe ApiDbContext.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using Microsoft.EntityFrameworkCore;\nusing Net.WebApi.Globalexcpetions.Models;\n\nnamespace Net.WebApi.Globalexcpetions.Data;\n\npublic class ApiDbContext :DbContext\n{\n    public ApiDbContext(DbContextOptions&lt;ApiDbContext> options) : base(options) { }\n    public DbSet&lt;Employee> Employees { get; set; }\n}<\/pre>\n\n\n\n<p>Maintenant, nous devons ajouter la cha\u00eene de connexion dans le appsettings.json<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\"ConnectionStrings\": {\n    \"SampleDbConnection\": \"User ID =mohamad;Password=12345678;Server=localhost;Port=5432;Database=sampledb; Integrated Security=true;Pooling=true;\"\n  }<\/pre>\n\n\n\n<p>Ensuite, nous devons mettre \u00e0 jour notre program.cs<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">builder.Services.AddEntityFrameworkNpgsql().AddDbContext&lt;ApiDbContext>(opt =>\n        opt.UseNpgsql(builder.Configuration.GetConnectionString(\"SampleDbConnection\")));\n<\/pre>\n\n\n\n<p>Une fois que nous les ajoutons, nous pouvons faire notre migration<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">dotnet ef migrations add \"initial_migration\"\ndotnet ef database update<\/pre>\n\n\n\n<p>Cr\u00e9ons maintenant les EmployeeServices dans le r\u00e9pertoire racine de notre application, cr\u00e9ons un nouveau dossier appel\u00e9 Services et dans ce dossier, nous allons cr\u00e9er une nouvelle interface appel\u00e9e IEmployeeService<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using Net.WebApi.Globalexcpetions.Models;\n\nnamespace Net.WebApi.Globalexcpetions.Services;\n\npublic interface IEmployeeService\n{\n    public Task&lt;IEnumerable&lt;Employee>> GetEmployees();\n    public Task&lt;Employee?> GetEmployeeById(int id);\n    public Task&lt;Employee> AddEmployee(Employee Employee);\n    public Task&lt;Employee> UpdateEmployee(Employee Employee);\n    public Task&lt;bool> DeleteEmployee(int Id);\n}\n<\/pre>\n\n\n\n<p>Maintenant, dans le m\u00eame dossier, nous allons cr\u00e9er une nouvelle classe appel\u00e9e EmployeeService<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using Microsoft.EntityFrameworkCore;\nusing Net.WebApi.Globalexcpetions.Data;\nusing Net.WebApi.Globalexcpetions.Models;\n\nnamespace Net.WebApi.Globalexcpetions.Services;\n\npublic class EmployeeService : IEmployeeService\n{\n    private readonly ApiDbContext _dbContext;\n\n    public EmployeeService(ApiDbContext dbContext)\n    {\n        _dbContext = dbContext;\n    }\n\n    public async Task&lt;IEnumerable&lt;Employee>> GetEmployees()\n    {\n        return await _dbContext.Employees.ToListAsync();\n    }\n\n    public async Task&lt;Employee?> GetEmployeeById(int id)\n    {\n        return await _dbContext.Employees.FirstOrDefaultAsync(x => x.Id == id);\n    }\n\n    public async Task&lt;Employee> AddEmployee(Employee Employee)\n    {\n        var result = _dbContext.Employees.Add(Employee);\n        await _dbContext.SaveChangesAsync();\n        return result.Entity;\n    }\n\n    public async Task&lt;Employee> UpdateEmployee(Employee Employee)\n    {\n        var result = _dbContext.Employees.Update(Employee);\n        await _dbContext.SaveChangesAsync();\n        return result.Entity;\n    }\n\n    public async Task&lt;bool> DeleteEmployee(int Id)\n    {\n        var filteredData = _dbContext.Employees.FirstOrDefault(x => x.Id == Id);\n        var result = _dbContext.Remove(filteredData);\n        await _dbContext.SaveChangesAsync();\n        return result != null ? true : false;\n    }\n}\n<\/pre>\n\n\n\n<p>Mettons maintenant \u00e0 jour notre Program.cs afin que nos EmployeeServices soient inject\u00e9s dans notre conteneur Dependency Inject<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">builder.Services.AddScoped&lt;IEmployeeService, EmployeeService>();<\/pre>\n\n\n\n<p>Maintenant, cr\u00e9ons notre EmployessController, \u00e0 l&rsquo;int\u00e9rieur du dossier du contr\u00f4leur, nous allons cr\u00e9er une nouvelle classe appel\u00e9e EmployessController et ajouterons ce qui suit<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using Microsoft.AspNetCore.Mvc;\nusing Net.WebApi.Globalexcpetions.Models;\nusing Net.WebApi.Globalexcpetions.Services;\n\nnamespace Net.WebApi.Globalexcpetions.Controllers;\n\n[ApiController]\n[Route(\"[controller]\")]\npublic class EmployeesController : ControllerBase\n{\n    private readonly ILogger&lt;EmployeesController> _logger;\n    private readonly IEmployeeService _employeeServices;\n\n    public EmployeesController(\n        ILogger&lt;EmployeesController> logger,\n        IEmployeeService employeeServices)\n    {\n        _logger = logger;\n        _employeeServices = employeeServices;\n    }\n    [HttpGet(\"employeelist\")]\n    public async Task&lt;IEnumerable&lt;Employee>> employeeList()\n    {\n        var employeeList = await _employeeServices.GetEmployees();\n        return employeeList;\n    }\n\n    [HttpGet(\"getemployeebyid\")]\n    public async Task&lt;IActionResult> GetemployeeById(int Id)\n    {\n        _logger.LogInformation($\"Fetch employee with ID: {Id} from the database\");\n        var employee = await _employeeServices.GetEmployeeById(Id);\n        if (employee == null)\n        {\n            \/\/throw new Notfound($\"employee ID {Id} not found.\");\n            return NotFound();\n        }\n        _logger.LogInformation($\"Returning employee with ID: {employee.Id}.\");\n        return Ok(employee);\n    }\n\n    [HttpPost(\"addemployee\")]\n    public async Task&lt;IActionResult> Addemployee(Employee employee)\n    {\n        var result = await _employeeServices.AddEmployee(employee);\n        return Ok(result);\n    }\n\n    [HttpPut(\"updateemployee\")]\n    public async Task&lt;IActionResult> Updateemployee(Employee employee)\n    {\n        var result = await _employeeServices.UpdateEmployee(employee);\n        return Ok(result);\n    }\n\n    [HttpDelete(\"deleteemployee\")]\n    public async Task&lt;bool> Deleteemployee(int Id)\n    {\n        return await _employeeServices.DeleteEmployee(Id);\n    }\n}\n<\/pre>\n\n\n\n<p>Ajoutons maintenant un nouveau dossier appel\u00e9 Exceptions qui sera utilis\u00e9 pour g\u00e9rer toutes nos exceptions<\/p>\n\n\n\n<p>Nous ajouterons les exceptions suivantes<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">namespace Net.WebApi.Globalexcpetions.Exceptions;\n\npublic class BadRequestException : Exception\n{\n    public BadRequestException(string message) : base(message)\n    { }\n}<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">namespace Net.WebApi.Globalexcpetions.Exceptions;\n\npublic class KeyNotFoundException : Exception\n{\n    public KeyNotFoundException(string message) : base(message)\n    { }\n}<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">namespace Net.WebApi.Globalexcpetions.Exceptions;\n\npublic class NotFoundException : Exception\n{\n    public NotFoundException(string message) : base(message)\n    { }\n}<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">namespace Net.WebApi.Globalexcpetions.Exceptions;\n\npublic class NotImplementedException : Exception\n{\n    public NotImplementedException(string message) : base(message)\n    { }\n}<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">namespace Net.WebApi.Globalexcpetions.Exceptions;\n\npublic class UnauthorizedAccessException : Exception\n{\n    public UnauthorizedAccessException(string message) : base(message)\n    { }\n}<\/pre>\n\n\n\n<p>Maintenant que nos exceptions ont \u00e9t\u00e9 ajout\u00e9es, nous devons ajouter un dossier au r\u00e9pertoire racine de notre application appel\u00e9 configurations o\u00f9 nous pouvons construire notre GlobalErrorHandlingMiddleware<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using System.Net;\nusing System.Text.Json;\nusing Net.WebApi.Globalexcpetions.Exceptions;\n\nusing KeyNotFoundException = Net.WebApi.Globalexcpetions.Exceptions.KeyNotFoundException;\nusing NotImplementedException = Net.WebApi.Globalexcpetions.Exceptions.NotImplementedException;\nusing UnauthorizedAccessException = Net.WebApi.Globalexcpetions.Exceptions.UnauthorizedAccessException;\n\nnamespace Net.WebApi.Globalexcpetions.Exceptions;\npublic class GlobalErrorHandlingMiddleware\n{\n    private readonly RequestDelegate _next;\n\n    public GlobalErrorHandlingMiddleware(RequestDelegate next)\n    {\n        _next = next;\n    }\n\n    public async Task Invoke(HttpContext context)\n    {\n        try\n        {\n            await _next(context);\n        }\n        catch (Exception ex)\n        {\n            await HandleExceptionAsync(context, ex);\n        }\n    }\n\n    private static Task HandleExceptionAsync(HttpContext context, Exception exception)\n    {\n        HttpStatusCode status;\n        var stackTrace = string.Empty;\n        string message;\n\n        var exceptionType = exception.GetType();\n\n        if (exceptionType == typeof(BadRequestException))\n        {\n            message = exception.Message;\n            status = HttpStatusCode.BadRequest;\n            stackTrace = exception.StackTrace;\n        }\n        else if (exceptionType == typeof(NotFoundException))\n        {\n            message = exception.Message;\n            status = HttpStatusCode.NotFound;\n            stackTrace = exception.StackTrace;\n        }\n        else if (exceptionType == typeof(NotImplementedException))\n        {\n            status = HttpStatusCode.NotImplemented;\n            message = exception.Message;\n            stackTrace = exception.StackTrace;\n        }\n        else if (exceptionType == typeof(UnauthorizedAccessException))\n        {\n            status = HttpStatusCode.Unauthorized;\n            message = exception.Message;\n            stackTrace = exception.StackTrace;\n        }\n        else if (exceptionType == typeof(KeyNotFoundException))\n        {\n            status = HttpStatusCode.Unauthorized;\n            message = exception.Message;\n            stackTrace = exception.StackTrace;\n        }\n        else\n        {\n            status = HttpStatusCode.InternalServerError;\n            message = exception.Message;\n            stackTrace = exception.StackTrace;\n        }\n\n        var exceptionResult = JsonSerializer.Serialize(new { error = message, stackTrace });\n        context.Response.ContentType = \"application\/json\";\n        context.Response.StatusCode = (int)status;\n\n        return context.Response.WriteAsync(exceptionResult);\n    }\n}\n<\/pre>\n\n\n\n<p>Le GlobalErrorHandlingMiddleware est utilis\u00e9 pour fournir plus de contr\u00f4le sur les exceptions que l&rsquo;application va g\u00e9n\u00e9rer<\/p>\n\n\n\n<p>S&rsquo;il y a des erreurs dans une demande entrante, le GlobalErrorHandlingMiddleware traitera l&rsquo;erreur<\/p>\n\n\n\n<p>Cr\u00e9ons maintenant ApplicationBuilderExtension afin que nous puissions injecter notre middleware dans le dossier Services<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using Net.WebApi.Globalexcpetions.Exceptions;\n\nnamespace Net.WebApi.Globalexcpetions.Configurations;\n\npublic static class ApplicationBuilderExtensions\n{\n    public static IApplicationBuilder AddGlobalErrorHandler(this IApplicationBuilder applicationBuilder)\n        => applicationBuilder.UseMiddleware&lt;GlobalErrorHandlingMiddleware>();\n}\n<\/pre>\n\n\n\n<p>Injectons maintenant ceci dans le Program.cs<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">app.AddGlobalErrorHandler();\n<\/pre>\n\n\n\n<p>Veuillez fournir vos commentaires et poser toute question.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"aioseo-derniers-articles\">Derniers Articles<\/h2>\n\n\n\n<ul id=\"block-957e2f94-bcbc-4609-b8f3-4ca3d686660e\" class=\"wp-block-list\">\n<li><a href=\"https:\/\/oussamasaidi.com\/en\/hangfire-avec-asp-net-core\/\">Hangfire avec ASP.NET Core<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/oussamasaidi.com\/en\/automapper-net-core\/\">Premiers pas avec AutoMapper dans ASP.NET Core<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/oussamasaidi.com\/en\/serilog-in-aspnet-core-3-1\/\">Serilog dans ASP.NET Core 3.1-La journalisation structur\u00e9e simplifi\u00e9e<\/a><\/li>\n<\/ul>\n\n\n\n<div class=\"wp-container-6 wp-block-columns alignwide\">\n<div class=\"wp-container-5 wp-elements-e1ba0e3d9d30b7fec5c25e47c471e6ef wp-block-column has-text-color has-background has-link-color\" style=\"background-color:#c0ebf1;color:#000000;padding-top:2em;padding-right:2em;padding-bottom:2em;padding-left:2em\">\n<h2 id=\"patron\" style=\"font-size:40px\"><strong>Vous aimez le contenu&nbsp;?<\/strong><\/h2>\n\n\n\n<p class=\"has-normal-font-size\"><strong>Si vous aimez mes articles, pensez \u00e0 m\u2019acheter quelques caf\u00e9s !<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity is-style-wide\">\n\n\n\n<div class=\"wp-container-4 is-horizontal is-content-justification-center wp-block-buttons alignfull\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-100\"><a class=\"wp-block-button__link has-white-color has-text-color has-background no-border-radius\" href=\"https:\/\/www.buymeacoffee.com\/oussamasaiI\" style=\"background-color:#000000\" target=\"_blank\" rel=\"noreferrer noopener\">Achetez-moi un caf\u00e9<\/a><\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>.NET 6 &#8211; Gestion des exceptions globales de l&rsquo;API Web<\/p>","protected":false},"author":1,"featured_media":811,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[40,41,56,60,61],"tags":[],"ppma_author":[286],"class_list":["post-810","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-netcore","category-c","category-c-2","category-swagger-ui","category-web-api"],"acf":[],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/oussamasaidi.com\/wp-content\/uploads\/2023\/02\/net-6-web-api-global-exceptions-handling.webp","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":1639,"url":"https:\/\/oussamasaidi.com\/en\/restful-api-mastery-best-practices-with-asp-net-core\/","url_meta":{"origin":810,"position":0},"title":"RESTful API Best Practices with ASP.NET Core","author":"Saidi Oussama","date":"December 16, 2025","format":false,"excerpt":"Professional Best Practices, Versioning Strategies & Advanced Serialization (Part 1) In this blog Introduction: Building Enterprise-Grade RESTful APIs with ASP.NET Core1. RESTful APIs in the Modern ASP.NET Core EcosystemWhy REST Still Dominates2. REST Architectural Constraints Every ASP.NET Core API Must EnforceClient\u2013Server SeparationStatelessnessUniform Interface3. Establishing a Clean and Scalable ASP.NET Core\u2026","rel":"","context":"In &quot;.Net Core&quot;","block_context":{"text":".Net Core","link":"https:\/\/oussamasaidi.com\/en\/category\/netcore\/"},"img":{"alt_text":"RESTful API Mastery","src":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-cover-scaled.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-cover-scaled.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-cover-scaled.png?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-cover-scaled.png?resize=700%2C400&ssl=1 2x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-cover-scaled.png?resize=1050%2C600&ssl=1 3x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-cover-scaled.png?resize=1400%2C800&ssl=1 4x"},"classes":[]},{"id":1325,"url":"https:\/\/oussamasaidi.com\/en\/building-professional-modern-api-documentation-in-net-core-with-scalar\/","url_meta":{"origin":810,"position":1},"title":"Building Professional, Modern API Documentation in .NET Core with Scalar","author":"Saidi Oussama","date":"November 19, 2025","format":false,"excerpt":"Introduction In today\u2019s software ecosystem, APIs are everywhere. Whether you are building a mobile application, a microservices architecture, or an internal company platform, your API is often the backbone of the system. But even the best API becomes useless if developers cannot understand how to consume it. This is why\u2026","rel":"","context":"In &quot;.Net Core&quot;","block_context":{"text":".Net Core","link":"https:\/\/oussamasaidi.com\/en\/category\/netcore\/"},"img":{"alt_text":"Building Professional, Modern API Documentation in .NET Core with Scalar","src":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/11\/Building-Professional-Modern-API-Documentation-in-.NET-Core-with-Scalar.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/11\/Building-Professional-Modern-API-Documentation-in-.NET-Core-with-Scalar.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/11\/Building-Professional-Modern-API-Documentation-in-.NET-Core-with-Scalar.png?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/11\/Building-Professional-Modern-API-Documentation-in-.NET-Core-with-Scalar.png?resize=700%2C400&ssl=1 2x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/11\/Building-Professional-Modern-API-Documentation-in-.NET-Core-with-Scalar.png?resize=1050%2C600&ssl=1 3x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/11\/Building-Professional-Modern-API-Documentation-in-.NET-Core-with-Scalar.png?resize=1400%2C800&ssl=1 4x"},"classes":[]},{"id":838,"url":"https:\/\/oussamasaidi.com\/en\/comment-implementer-authentification-cle-api-aspnet-core\/","url_meta":{"origin":810,"position":2},"title":".NET Core : impl\u00e9menter l\u2019authentification par cl\u00e9 API en C#","author":"Saidi Oussama","date":"August 22, 2024","format":false,"excerpt":"ContexteCr\u00e9ation de l'attribut de cl\u00e9 APIImpl\u00e9menter du filtre d'autorisation ApiKeyimpl\u00e9mentation de l'ApiKeyValidatorTester l'APIUtilisez le middlewareConclusionDerniers Articles Vous pouvez trouver le code source complet sur github Contexte Alors, qu\u2019est-ce que l\u2019authentification par cl\u00e9 API dans ASP.NET Core ? Prenons un exemple concret. Imaginez que vous ayez d\u00e9velopp\u00e9 un tableau de bord\u2026","rel":"","context":"In &quot;.Net Core&quot;","block_context":{"text":".Net Core","link":"https:\/\/oussamasaidi.com\/en\/category\/netcore\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2024\/07\/Capture00.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2024\/07\/Capture00.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2024\/07\/Capture00.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":1035,"url":"https:\/\/oussamasaidi.com\/en\/creer-un-chatbot-avec-deepseek-et-net-9-tutoriel-complet\/","url_meta":{"origin":810,"position":3},"title":"Cr\u00e9er un Chatbot avec DeepSeek et .NET 9 : Tutoriel Complet","author":"Saidi Oussama","date":"April 6, 2025","format":false,"excerpt":"Ce tutoriel vous guidera pas \u00e0 pas pour construire un chatbot utilisant l'API de DeepSeek avec .NET 9. Nous allons cr\u00e9er une application web de chatbot avec ASP.NET Core. Pr\u00e9requis\u00c9tape 1 : Cr\u00e9er une nouvelle application Web ASP.NET Core\u00c9tape 2 : Ajouter les packages n\u00e9cessaires\u00c9tape 3 : Cr\u00e9er les mod\u00e8les\u2026","rel":"","context":"In &quot;.Net Core&quot;","block_context":{"text":".Net Core","link":"https:\/\/oussamasaidi.com\/en\/category\/netcore\/"},"img":{"alt_text":"AI Chatbot with .net core","src":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/04\/https___dev-to-uploads.s3.amazonaws.com_uploads_articles_w4yx4rdp1ohuvcb96ypg.webp?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/04\/https___dev-to-uploads.s3.amazonaws.com_uploads_articles_w4yx4rdp1ohuvcb96ypg.webp?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/04\/https___dev-to-uploads.s3.amazonaws.com_uploads_articles_w4yx4rdp1ohuvcb96ypg.webp?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/04\/https___dev-to-uploads.s3.amazonaws.com_uploads_articles_w4yx4rdp1ohuvcb96ypg.webp?resize=700%2C400&ssl=1 2x"},"classes":[]},{"id":1714,"url":"https:\/\/oussamasaidi.com\/en\/https-oussamasaidi-com-restful-api-mastery-best-practices-with-asp-net-core-part-2\/","url_meta":{"origin":810,"position":4},"title":"RESTful API best practices\u00a0with ASP.NET Core Part 2","author":"Saidi Oussama","date":"December 20, 2025","format":false,"excerpt":"Testing, Performance, Security, Microservices & Deployment Introduction: From Solid Foundations to Production Excellence In Part 1 of RESTful API Mastery, we established the architectural and technical foundations required to build reliable, evolvable RESTful APIs with ASP.NET Core. However, a well-designed API only becomes truly valuable when it is tested, observable,\u2026","rel":"","context":"In &quot;.Net Core&quot;","block_context":{"text":".Net Core","link":"https:\/\/oussamasaidi.com\/en\/category\/netcore\/"},"img":{"alt_text":"RESTful API Mastery","src":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-2r.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-2r.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-2r.png?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-2r.png?resize=700%2C400&ssl=1 2x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-2r.png?resize=1050%2C600&ssl=1 3x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2025\/12\/restful-api-mastery-best-practices-with-asp-net-core-2r.png?resize=1400%2C800&ssl=1 4x"},"classes":[]},{"id":748,"url":"https:\/\/oussamasaidi.com\/en\/swagger-ui-asp-net-core-web-api\/","url_meta":{"origin":810,"position":5},"title":"Configuration et utilisation de Swagger UI dans ASP.NET Core Web API","author":"Saidi Oussama","date":"January 17, 2023","format":false,"excerpt":"Dans cet article, nous allons apprendre \u00e0 int\u00e9grer l'interface utilisateur Swagger UI dans une application API Web ASP.NET Core.\u00a0 Pour t\u00e9l\u00e9charger le code source de cet article, vous pouvez visiter notre d\u00e9p\u00f4t GitHub . Plongeons dedans. Pourquoi devrions-nous documenter notre APISwagger UI\/OpenAPIInt\u00e9gration de Swagger UI dans nos applicationsInstallation du paquetConfiguration\u2026","rel":"","context":"In &quot;.Net Core&quot;","block_context":{"text":".Net Core","link":"https:\/\/oussamasaidi.com\/en\/category\/netcore\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2023\/01\/swaggeruidotnetcore.jpg?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2023\/01\/swaggeruidotnetcore.jpg?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2023\/01\/swaggeruidotnetcore.jpg?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2023\/01\/swaggeruidotnetcore.jpg?resize=700%2C400&ssl=1 2x, https:\/\/i0.wp.com\/oussamasaidi.com\/wp-content\/uploads\/2023\/01\/swaggeruidotnetcore.jpg?resize=1050%2C600&ssl=1 3x"},"classes":[]}],"authors":[{"term_id":286,"user_id":1,"is_guest":0,"slug":"oussama_sa","display_name":"Saidi Oussama","avatar_url":{"url":"https:\/\/oussamasaidi.com\/wp-content\/uploads\/2022\/02\/001_001_cv1.jpg","url2x":"https:\/\/oussamasaidi.com\/wp-content\/uploads\/2022\/02\/001_001_cv1.jpg"},"author_category":"1","first_name":"Oussama","last_name":"SAIDI","user_url":"https:\/\/oussamasaidi.com","job_title":"Senior Fullstack .NET Developer","description":"I\u2019m a Senior Fullstack .NET Developer specializing in building scalable, high-performance web applications with .NET, C#, and modern frontend frameworks like React.js. I\u2019m passionate about clean architecture, automated testing, and sharing knowledge through blogs and tutorials."}],"_links":{"self":[{"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/posts\/810","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/comments?post=810"}],"version-history":[{"count":1,"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/posts\/810\/revisions"}],"predecessor-version":[{"id":1513,"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/posts\/810\/revisions\/1513"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/media\/811"}],"wp:attachment":[{"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/media?parent=810"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/categories?post=810"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/tags?post=810"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/oussamasaidi.com\/en\/wp-json\/wp\/v2\/ppma_author?post=810"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}