Asp.Net Core 2.2 Web Api Client ile CRUD İşlemleri 1

Kaldığımız yerden devam. Bir önceki yazımda Asp.Net Core 2.2 ile Web Api oluşturmuştuk. Şimdi bu oluşturduğumuz servisi nasıl kullanırız onu göreceğiz.

Solution da yeni bir proje ekliyoruz. Asp.NetCoreWepApi.Client isminde empty bir proje oluşturuyoruz.

Temel klasörler olan Controllers, Models, Views klasörlerini birde Client işlemleri için ClientManager isimli klasör oluşturalım.




















Kategoriye ait ürünlerin olduğu model sınıflarımızı oluşturalım.

    public class BaseEntity
    {
        public int Id { getset; }
        public bool IsActive { getset; }
        public string Description { getset; }
    }

   public class Product:BaseEntity
    {
        public string Name { getset; }
        public int Stock { getset; }
        public double Price { getset; }
        public int CategoryId { getset; }
        public virtual Category Category { getset; }
    }

 public class Category:BaseEntity
    {
        public Category()
        {
            Products = new HashSet<Product>();
        }

        public string CategoryName { getset; }
        public virtual ICollection<Product> Products { getset; }
    }


Oluşturacağımız sınıfların Generic bir yapıda olmasını sağlayacağız. Bunun için ClientManager klasöründe Interface isimli bir klasör daha oluşturup, içine IBaseClientManager isimli arayüzünü oluşturalım.

 public interface IBaseClientManager<TEntity> where TEntity:class
    {
        ICollection<TEntity> GetAll();
        Task<ICollection<TEntity>> GetAllAsync();
        TEntity GetById(int id);
        Task<TEntity> GetByIdAsync(int id);
        void Url(string baseUrl, string url);
        void Add(TEntity entity);
        void Update(int id, TEntity entity);
        void Delete(int id);
    } 

GET, PUT, POST ve DELETE işlemleri yapacağımız GetAll, Add, Update, Delete metotlarını oluşturduk.

ICategoryClientManager ve IProductClientManager arayüzlerine  uygulayalım.


 public interface ICategoryClientManager:IBaseClientManager<Category>
    {
    }

public interface IProductClientManager:IBaseClientManager<Product>
    {
    }


Daha sonra bu arayüzü miras alacak olan BaseClientManager sınıfımızı oluşturalım ve içine Api çağırımı için gerekli olan değişkenleri ekleyelim.

 public class BaseClientManager<TEntity> : IBaseClientManager<TEntity> where TEntity : class
    {
        private static string _baseUrl;
        static HttpClient _client;
        static string _url;

        public void Url(string baseUrl, string url)
        {
            _url = url;
            _baseUrl = baseUrl;
        }
}

Sınıfımıza Client metodunu ekleyelim. Bu metot ile her seferinde api çağırımı için gerekli olan Url bilgisi ve hangi formatta veriyi çekeceğiz onu yazıyoruz.


public void Client()
        {
            _client.BaseAddress = new Uri(_baseUrl);
            _client.DefaultRequestHeaders.Accept.Clear();
            _client.DefaultRequestHeaders.Accept.Add(new                                                                                      MediaTypeWithQualityHeaderValue("application/json"));
        }


Şimdi GetAll metodu ile verileri çekeceğiz.

// GET:

 public ICollection<TEntity> GetAll()
        {
            try
            {
                using (_client = new HttpClient())
                {
                    Client();
                    var response = _client.GetAsync($"{_url}").Result;
                    response.EnsureSuccessStatusCode();
                    return response.Content.ReadAsAsync<ICollection<TEntity>>().Result;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }


GetAllAsync metoduyla asenkron olarak verileri çekiyoruz.

// GET:

 public async Task<ICollection<TEntity>> GetAllAsync()
        {
            try
            {
                using (_client = new HttpClient())
                {
                    Client();
                    var response = _client.GetAsync($"{_url}").Result;
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsAsync<ICollection<TEntity>>();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }



// GET:

 public async Task<TEntity> GetByIdAsync(int id)
        {
            try
            {
                using (_client = new HttpClient())
                {
                    Client();
                    var response = _client.GetAsync($"{_url}/{id}").Result;
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsAsync<TEntity>();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }



// GET:

 public TEntity GetById(int id)
        {
            try
            {
                using (_client = new HttpClient())
                {
                    Client();
                    var response = _client.GetAsync($"{_url}/{id}").Result;
                    response.EnsureSuccessStatusCode();
                    return response.Content.ReadAsAsync<TEntity>().Result;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }



//  POST:

  public void Add(TEntity entity)
        {
            try
            {
                using (_client = new HttpClient())
                {
                    Client();
                    var response = _client.PostAsJsonAsync($"{ _url}", entity).Result;
                }
            }
            catch (Exception)
            {
                throw;
            }

        }



// PUT:

 public void Update(int id, TEntity entity)
        {
            try
            {
                using (_client = new HttpClient())
                {
                    Client();
                    var response = _client.PutAsJsonAsync($"{_url}/{id}", entity).Result;
                }             
            }
            catch (Exception)
            {
                throw;
            }

        }



// DELETE:

public void Delete(int id)
        {
            try
            {
                using (_client = new HttpClient())
                {
                    Client();
                    var response = _client.DeleteAsync($"{_url}/{id}").Result;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }


BaseClientManager artık hazır. Şimdi bu sınıfı miras alacak olan sınıfları oluşturalım.
   

    public class CategoryClientManager:BaseClientManager<Category>,ICategoryClientManager
    {
    }

    public class ProductClientManager:BaseClientManager<Product>,IProductClientManager
    {
    }


Şimdi görüntü sayfaları için View Modellerimizi oluşturalım.


    public class BaseViewModel
    {
        public int Id { get; set; }
        public bool IsActive { get; set; }
        public string Description { get; set; }
    }


public class EditProductViewModel:BaseViewModel
    {
        public string Name { get; set; }
        public int Stock { get; set; }
        public double Price { get; set; }
        public int CategoryId { get; set; }
        public virtual IEnumerable<Category> Categories { get; set; }
    }

 public class EditCategoryViewModel:BaseViewModel
    {
        public EditCategoryViewModel()
        {
            Products = new HashSet<Product>();
        }

        public string CategoryName { get; set; }
        public virtual ICollection<Product> Products { get; set; }
        public virtual ICollection<Category> Categories { get; set; }
    }

yazının devamını Asp.Net Core 2.2 Web Api Client ile CRUD İşlemleri 2 sayfasından bakabilirsiniz.

Yorumlar

Bu blogdaki popüler yayınlar

İç İçe Bağımlı DropdownListFor (Cascading)

Asp.Net Core View Components Kullanımı

Partial - RenderPartial - Html.Action - Html.RenderAction Kullanımı