VueJs’de Vue Resource Kullanarak .Net Core Web Api Servisi ile Haberleşmek
Selamlar, bu makalede VueJs‘de Vue Resource kullanarak hazırlamış olduğumuz Web Api servisi ile nasıl haberleşiriz onun üzerine konuşuyor olacağız.
Uygulamamız kitap satışı yapan bir işletmenin elinde bulunan kitapların uygulama üzerinden yönetilmesini sağlamak olacak.Uygulamamız inşa ederken front-end tarafta VueJs backend tarafta ise Asp.Net Core Web Api kullanıyor olacağız. Çok detaylı işlemlere girmeden basit crud işlemler ile konuyu kavramaya çalışacağız.
İlk olarak servis yapımızı tanıyarak başlayalım. Servis inşa ederken önemli konulardan bir tanesi ortak dönüş modelidir.Yazmış olduğumuz servis bir çok farklı uygulama ve platform tarafından tüketiliyor olabilir. Bu noktada gelen tüm isteklere dönülen cevapların net ve anlaşılır olması hayati bir önem taşımaktadır. ServiceResponse.cs uygulama genelinde kullanacağımız ortak dönüş modelimiz olacak.
1 2 3 4 5 6 | public class ServiceResponse<T> where T : class, new() { public bool IsSuccessful { get; set; } public T Entity { get; set; } public string Message { get; set; } } |
BookListDto.cs
1 2 3 4 5 6 7 8 9 | public class BookListDto { public int Id { get; set; } public string Name { get; set; } public int NumberOfPage { get; set; } public string CategoryName { get; set; } public string AuthorName { get; set; } public string PublisherName { get; set; } } |
BookDto.cs
1 2 3 4 5 6 7 8 9 | public class BookDto { public int Id { get; set; } public string Name { get; set; } public string NumberOfPage { get; set; } public string CategoryId { get; set; } public string AuthorId { get; set; } public string PublisherId { get; set; } } |
Servisimiz temel seviyede 5 adet method sunmakta. Methodların işlevleri isimlerinden anlaşılır olsa da aşağıda her bir metodun hangi işlemi gerçekleştirdiğini ve servise ait tüm kodları bulabilirsiniz. Servisimizin son hali bu şekilde olacaktır.
- Delete:Kitap silme işlemi gerçekleştirir.
- Get:Tüm kitaplar listesini döner.
- Add:Kitap ekleme işlemi gerçekleştirir.
- GetBookById:Tek bir kitap kaydını getirir
- Update:Kitap düzenleme işlemi gerçekleştirir.
NOT:Mapping işlemleri için AutoMapper kütüphanesi kullanılmıştır. AutoMapper hakkında bilgi edinmek isterseniz buradaki linkten AutoMapper ile ilgili yazıma ulaşabilirsiniz.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | [ApiController] public class BooksController : ControllerBase { BookStoreContext _bookStoreContext; IMapper _mapper; public BooksController(BookStoreContext bookStoreContext, IMapper mapper) { _bookStoreContext = bookStoreContext; _mapper = mapper; } [HttpGet] [Route("get-all-book")] public async Task<ActionResult<ServiceResponse<List<BookListDto>>>> Get() { var response = new ServiceResponse<List<BookListDto>>(); try { var books = await _bookStoreContext.Books.Include("Categories").Include("Publishers").Include("Authors").Select(x => new BookListDto() { Id = x.Id, Name = x.Name, CategoryName = x.Categories.Name, PublisherName = x.Publishers.Name, AuthorName = x.Authors.Name, NumberOfPage = x.NumberOfPage }).ToListAsync(); response.IsSuccessful = true; response.Entity = books; response.Message = "Book listing successful"; return Ok(response); } catch (Exception exception) { response.Message = exception.Message; response.Entity = null; response.IsSuccessful = false; return BadRequest(response); } } [HttpPost] [Route("add-book")] public async Task<ActionResult<ServiceResponse<BookDto>>> Add([FromBody]BookDto booksDto) { var response = new ServiceResponse<BookDto>(); try { var entry = _bookStoreContext.Entry(_mapper.Map<Books>(booksDto)); entry.State = EntityState.Added; await _bookStoreContext.SaveChangesAsync(); response.Entity = _mapper.Map<BookDto>(entry.Entity); response.IsSuccessful = true; response.Message = "Book registration successful"; return Ok(response); } catch (Exception exception) { response.Message = exception.Message; response.Entity = null; response.IsSuccessful = false; return BadRequest(response); } } [HttpDelete] [Route("delete-book/{bookId}")] public async Task<ActionResult<ServiceResponse<BookDto>>> Delete(int bookId) { var response = new ServiceResponse<BookDto>(); try { var book = await _bookStoreContext.Books.FirstOrDefaultAsync(x => x.Id == bookId); if (book == null) { response.Message = "Book Record not found"; response.Entity = null; response.IsSuccessful = false; return NotFound(response); } var entry = _bookStoreContext.Entry(book); entry.State = EntityState.Deleted; await _bookStoreContext.SaveChangesAsync(); response.Entity = _mapper.Map<BookDto>(entry.Entity); response.IsSuccessful = true; response.Message = "Book deletion successful"; return Ok(response); } catch (Exception exception) { response.Message = exception.Message; response.Entity = null; response.IsSuccessful = false; return BadRequest(response); } } [HttpPut] [Route("update-book")] public async Task<ActionResult<ServiceResponse<BookDto>>> Update([FromBody]BookDto booksDto) { var response = new ServiceResponse<BookDto>(); try { var entry = _bookStoreContext.Entry(_mapper.Map<Books>(booksDto)); entry.State = EntityState.Modified; await _bookStoreContext.SaveChangesAsync(); response.Entity = _mapper.Map<BookDto>(entry.Entity); response.IsSuccessful = true; response.Message = "Book editing successful"; return Ok(response); } catch (Exception exception) { response.Message = exception.Message; response.Entity = null; response.IsSuccessful = false; return BadRequest(response); } } [HttpGet] [Route("get-book/{bookId}")] public async Task<ActionResult<ServiceResponse<BookDto>>> GetBook(int bookId) { var response = new ServiceResponse<BookDto>(); try { var book = await _bookStoreContext.Books.FirstOrDefaultAsync(x => x.Id == bookId); response.Entity = _mapper.Map<BookDto>(book); response.IsSuccessful = true; response.Message = "Book editing successful"; return Ok(response); } catch (Exception exception) { response.Message = exception.Message; response.Entity = null; response.IsSuccessful = false; return BadRequest(response); } } } |
Servisimizi inşa ettik.Şimdi sıra geldi servisimizi tüketecek olarak VueJs projemizde Vue Resource yapılandırması gerçekleştirmeye. İlk olarak aşağıdaki komutu kullanarak Vue Resource‘u projemize dahil ediyoruz.
1 | npm install vue-resource |
Paket başarılı şekilde yüklendikten sonra main.js içerisine gelip Vue Resource‘uimport ediyoruz. İmport işleminde sonra Vue Resource‘u proje genelinde kullanıma hazır hale getirmiş oluyoruz.
1 2 3 | import VueResource from 'vue-resource' Vue.use(VueResource); Vue.http.options.root="https://localhost:44344/"; |
NOT:Vue.http.options.root yapılandırmasının amacı VueJs tarafında servisimize istek gönderirken her endpoint’in başına “https://localhost:44344/” yazmamak için global bir tanımlama yaptık.
App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | <template> <div id="app"> <div class="container"> <br> <h3>{{title}}</h3> <br> <form id="book-form"> <div class="col-md-12"> <div class="row"> <div class="form-group col-md-6"> <label>Kitap İsmi</label> <input type="text" class="form-control" v-model="booksDto.name"> </div> <div class="form-group col-md-6"> <label>Sayfa Sayısı</label> <input type="text" class="form-control" v-model="booksDto.numberOfPage"> </div> </div> <div class="row"> <div class="form-group col-md-6"> <label>Yazar Seçiniz</label> <select class="form-control" v-model="booksDto.authorId"> <option value="1">Author 1</option> <option value="2">Author 2</option> <option value="3">Author 3</option> <option value="4">Author 4</option> <option value="5">Author 5</option> </select> </div> <div class="form-group col-md-6"> <label>Yayın Evi Seçiniz</label> <select class="form-control" v-model="booksDto.publisherId"> <option value="1">Publisher 1</option> <option value="2">Publisher 2</option> <option value="3">Publisher 3</option> <option value="4">Publisher 4</option> <option value="5">Publisher 5</option> </select> </div> </div> <div class="row"> <div class="form-group col-md-12"> <label>Kategori Seçiniz</label> <select class="form-control" v-model="booksDto.categoryId"> <option value="1">Category 1</option> <option value="2">Category 2</option> <option value="3">Category 3</option> <option value="4">Category 4</option> <option value="5">Category 5</option> </select> </div> <div class="form-group col-md-6"> <button type="button" v-if="!buttonType" @click="addBook" class="btn btn-success">Kaydet</button> <button type="button" v-if="buttonType" @click="updateBook" class="btn btn-primary">Güncelle</button> <button type="button" v-if="buttonType" @click="cancel" class="btn btn-dark">İptal</button> </div> </div> </div> </form> <table class="table"> <thead> <tr> <th scope="col">Kitap İsmi</th> <th scope="col">Sayfa Sayısı</th> <th scope="col">Kategori</th> <th scope="col">Yazar</th> <th scope="col">Yayın Evi</th> <th scope="col">Sil</th> <th scope="col">Güncelle</th> </tr> </thead> <tbody> <tr v-for="(book,index) in bookList" @click.native="alertMessage"> <td>{{book.name}}</td> <td>{{book.numberOfPage}}</td> <td>{{book.categoryName}}</td> <td>{{book.authorName}}</td> <td>{{book.publisherName}}</td> <td> <button @click="deleteBook(book.id,index)" class="btn-danger btn-xs">Sil</button> </td> <td> <button @click="getByBookId(book.id)" class="btn-danger btn-xs">Güncelle</button> </td> </tr> </tbody> </table> </div> </div> </template> |
Tasarımımız hazır. Şimdi ise VueJs tarafında kullanacağımız nesnelerimizi tanımlıyoruz.Tüm kitapları Get ettiğimizde elimizde bulunan kitap listesini bookList nesnesine aktaracağız. Onun dışında Post,Put işlemlerinde ise booksDto nesnemizi kullanıyor olacağız.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | data() { return { booksDto: { id: 0, name: null, numberOfPage: 0, categoryId: 0, authorId: 0, publisherId: 0 }, bookList: { id: 0, name: null, numberOfPage: null, categoryName: null, authorName: null, publisherName: null }, buttonType: false, title: "Kitap Girişi" } }, |
main.js içerisinde yapmış olduğumuz Vue Resource yapılandırmasından sonra this.$http syntax‘ı ile artık Vue Resource‘un bize sunmuş olduğu hazır methodlar üzerinden servisimize istekler göndermeye hazırız.
Kodumuzu inceleyecek olursak this.$http syntax‘ı üzerinden servisimize göndermek istediğimiz istek türüne göre POST,PUT,DELETE,GET vue resource tarafından bize sunulan hazır http metodunun çağırımını gerçekleştiriyoruz.Göndreceğimiz isteğe göre parametrelerimizi geçip dönen cevabı then kısmında yakalıyoruz ve servisten dönen cevabı elde etmiş oluyoruz. Sizde dilerseniz uygulamayı indirip kendiniz front-end ve back-end tarafta geliştirmeler yapabilirsiniz.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | methods: { addBook() { const self=this; this.$http.post("add-book", self.booksDto).then(function(response) { if(response.body.isSuccessful == true){ this.getAllBooks(); this.clear(); } else alert("Ekleme işlemi başarısız"); }); }, deleteBook(id, index) { this.$http.delete("delete-book/" + id).then(function(response) { if(response.body.isSuccessful == true){ this.bookList.splice(index, 1); this.getAllBooks(); } else alert("Silme işlemi başarısız"); }); }, getBook(id) { this.$http.get("get-book/" + id).then(function(response) { this.booksDto=response.body.entity; this.buttonType=true this.title="Kitap Düzenle"; }); }, updateBook() { const self=this; this.$http.put("update-book", self.booksDto).then(function(response) { if(response.body.isSuccessful == true){ this.buttonType=false this.clear(); this.getAllBooks(); } else alert("Düzenleme işlemi başarısız"); }); }, getAllBooks() { this.$http.get("get-all-book").then(function(response) { this.bookList=response.body.entity; }); }, clear() { this.buttonType=false; Object.keys(this.booksDto).forEach(key => { this.booksDto[key]='' }); this.title="Kitap Girişi"; }, }, mounted() { this.getAllBooks(); }, } |
Benim bu makalede aktaracaklarım bu kadar. Umarım faydalık bir yazı olmuştur.Bir başka makalede görüşmek dileğiyle hoşçakalın 🙂
Son Yorumlar