# ExceptionMiddleware

Bu Dökümantasyon da WepAPI returnlerinin Startup clasına eklenecek olan bir Middleware ile yönetilmesi anlatılmıştır.

Extensions folderının içeirine aşağıdaki classlar açılır

![](/files/f4V2wd9l933n3EcwGvGq)

Claslaın içleri şu şekildedir.

```
// DtResponse

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BSS_B2B_API.Extensions.ResponseModel
{
    public class DtResponse<T>
    {
        public bool IsSuccess { get; set; } = true;
        public string Message { get; set; }
        public T Data { get; set; }

    }
}

// DtResponseList

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BSS_B2B_API.Extensions.ResponseModel
{
    public class DtResponseList<T>
    {
        public bool IsSuccess { get; set; } = true;
        public string Message { get; set; }
        public List<T> Data { get; set; }
    }
}


//ErorDetails
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BSS_B2B_API.Extensions
{
    public class ErorDetails
    {
        public bool IsSuccess { get; set; }
        public string Message { get; set; }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }
}


//ExceptionMiddleware

using BSS_B2B_API.Extensions.ResponseModel;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace BSS_B2B_API.Extensions
{
    public class ExceptionMiddleware
    {
        private RequestDelegate _next;

        public ExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            DtResponseList<object> result = new();
            try
            {
                await _next(httpContext);
            }
            catch (Exception e)
            {
                await HandleExceptionAsync(httpContext, e);
            }
        }

        private Task HandleExceptionAsync(HttpContext httpContext, Exception e)
        {
            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            //httpContext.Response.StatusCode = (int)HttpStatusCode.OK;

            string message = e.Message;

            return httpContext.Response.WriteAsync(new ErorDetails
            {
                IsSuccess = false,
                Message = message
            }.ToString());
        }




    }
}


//ExceptionMiddlewareExtensions

using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BSS_B2B_API.Extensions
{
    public static class ExceptionMiddlewareExtensions
    {

        public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)
        {
            app.UseMiddleware<ExceptionMiddleware>();
        }

    }
}
```

Startup içerisine aşağıdaki kod yazılır

```
app.ConfigureCustomExceptionMiddleware();
```

![](/files/22L1FCq5SONhIJK4v5bX)

Yukarıda işlemlerden sonra Controller lar yazılır

örnek olarak 2 tane controller fotoğrafı eklenmiştir.

![](/files/7bikUnZe5ufCRwOZDqUd)

![](/files/7EFjxl3J6NCJUMYQIA6l)

```
// TEK BİR DATA DÖNDÜRMAK İÇİN
         [HttpGet("ProfilPageNew")]
        public async Task<IActionResult> ProfilPageNew()
        {
            //var firmId = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(x => x.Type == "FirmaID").Value;
            var firmId = 27576;

            DtResponse<object> result = new();

            using var connection = new SqlConnection("Data Source=185.122.203.104,1433;Database=DursunBatiDB; Integrated Security=false; User Id=Maliyet; Password=BssYazilim**2020");

            var firmaTemel = await connection.QueryFirstAsync<Company>($@"exec spB2B_ProfilBilgileri @firmaID={firmId}");

            var firmaAdress = await connection.QueryAsync<string>($@"exec spB2B_ProfilAdresler @firmaID={firmId}");

            result.Data = new { firmaTemel = firmaTemel, firmaAdres = firmaAdress };

            return Ok(result);
        }
        
        // LİST DÖNDÜRMAK İÇİN
          [HttpPost("TeklifTalepListesi")]
        public async Task<IActionResult> TeklifTalepListesi(TeklifTalepViewModel model)
        {
            //var firmId = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(x => x.Type == "FirmaID").Value;
            DtResponseList<TeklifTalep> result = new();            
            var firmId = 27575;

            using var connection = new SqlConnection("Data Source=185.122.203.104,1433;Database=DursunBatiDB; Integrated Security=false; User Id=Maliyet; Password=BssYazilim**2020");

            var teklifTalepList = await connection.QueryAsync<TeklifTalep>($@"exec spB2B_TeklifTalepler
                                                                         @firmaID={firmId}
	                                                                    ,@TalepTarihiBaslangic='{model.TalepTarihiBaslangic.ToString("yyy-MM-dd")}'
	                                                                    ,@TalepTarihiBitis ='{model.TalepTarihiBitis.ToString("yyy-MM-dd")}'
	                                                                    ,@TerminTarihiBaslangic ='{model.TerminTarihiBaslangic.ToString("yyy-MM-dd")}'
	                                                                    ,@TerminTarihiBitis ='{model.TerminTarihiBitis.ToString("yyy-MM-dd")}'
	                                                                    ,@TeklifGrupNo ='{model.TeklifGrupNo}'
	                                                                    ,@TalepDurum ={model.TalepDurum}");

            result.Data = teklifTalepList.ToList();
            return Ok(result);
        }
```

Burada yapılan işlem özet olarak şu şekildedir.

Erorr işlemi ExceptionMiddleware içerisinde yönetilecektir. WepAPI success geldiğinde ise controller içerisinde istenilen model ile döndürülülecektir. Biz burada liste ve obje olarak 2 türde veri döndürdüğümüz için 2 model oluşturduk.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ridvanorun.gitbook.io/asp-net-core/exceptionmiddleware.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
