> For the complete documentation index, see [llms.txt](https://ridvanorun.gitbook.io/asp-net-core/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ridvanorun.gitbook.io/asp-net-core/exceptionmiddleware.md).

# 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

![](https://1392128399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MR9wwvmI8SJVJgLR_0N%2Fuploads%2Frm8Yv0ONXCe12n8vnfXk%2Fimage.png?alt=media\&token=d4d9e097-649f-4760-8417-81212544c5c6)

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();
```

![](https://1392128399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MR9wwvmI8SJVJgLR_0N%2Fuploads%2FpyTJDxWDprsiFZyAfw0p%2Fimage.png?alt=media\&token=ac5214ff-2880-4cc6-8f0c-8bcab2379f95)

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

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

![](https://1392128399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MR9wwvmI8SJVJgLR_0N%2Fuploads%2FFqcnruWbKJ0ym8jvKsKs%2Fimage.png?alt=media\&token=65dbe02e-d7ce-4b0e-a9bd-95ed3871a3e5)

![](https://1392128399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MR9wwvmI8SJVJgLR_0N%2Fuploads%2Fq6RwA9dalPyXTAAjlJw4%2Fimage.png?alt=media\&token=f466a462-c186-4e1f-b201-e9bbda37aa9e)

```
// 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.
