Web Api ExceptionFilterAttribute Kullanımı

Try catch blokları ile yaptığımız işlem kullanışlı değil yani her method için gelerek Try Catch bloğu yazmak istemeyiz.

API’de hata geldiği zaman bunu tek bir noktadan yönetmek istiyoruz.

I. Project SağTık>Add>Folder : Attributes ismini verdik > Bu klasör içerisine ApiExceptionAttribute.cs ismine class ekledik, Bu class’ı ExceptionFilterAttribute class’ından miras alıyoruz. Bu class’taki OnException methodunu override ettik. (Bu sayede hata olunca şunu yap diyebileceğiz)

    public class ApiExceptionAttribute:ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
        ...
        }
    }

II. Controller’ımıza gittik ilgili method ya da tüm methodları kapsasın istiyorsak controller üzerine [ApiExceptionAttribute] ifadesini ekledik

    [ApiExceptionAttribute] //Bir hata meydan geldiği zaman (ön sqlServer bağlantı hatası) bizi Atrributes/ApiExceptionAttribute.cs/OnExcepton methoduna atacak
    public class LanguagesController : ApiController
    {
    ...
    }

III. Şimdi hata olunca ApiExceptionAttribute.cs class’ımıza düşebiliyoruz artık yapmamız gereken bu classta verilecek cevabı düzenlemek

    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        HttpResponseMessage errorResponse = new HttpResponseMessage(System.Net.HttpStatusCode.NotImplemented);
        errorResponse.ReasonPhrase = actionExecutedContext.Exception.Message;
        actionExecutedContext.Response = errorResponse;
        base.OnException(actionExecutedContext);
    }

IV. Attribute’u controller ya da method değil de Application seviyesine çıkarmak istersek yani tüm sayfalarda çalışsın

Project/App_Start/WebApiConfig.cs dosyamızda geldik ve filtre olarak ekledik

        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Filters.Add(new ApiExceptionAttribute());    //config'in Filtrelerinden ApiException classımızı ekledik böylece hatalar uygulama seviyesince yakalanabilecek

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

Yorum bırakın

WordPress.com'da bir web sitesi veya blog oluşturun

Yukarı ↑

WordPress.com ile böyle bir site tasarlayın
Başlayın