How can I implement an API Server with MVC

Miko Kagemori 46 Reputation points
2022-02-02T21:09:53.5+00:00

Got the solution

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,252 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
294 questions
{count} votes

Accepted answer
  1. Yijing Sun-MSFT 7,066 Reputation points
    2022-02-03T02:23:39.617+00:00

    Hi @Miko Kagemori ,
    According to your codes,I know that you are doing CRUD operations. Now,you need to interact with the data/information you expose to them.
    You need to use jquery ajax to implement it.

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Dox-chan 1 Reputation point
    2022-02-02T21:16:03.467+00:00

    Hey,
    for the ViewController to work, you need an ApiController
    It should look like this...

    public class storesController : ApiController
        {
            private BikeStoreEntities db = new BikeStoreEntities();
    
            // GET: api/stores
            public IHttpActionResult Getstores()
            {
                var stores = db.stores.Select(s => new StoreDTO() { 
                    store_id = s.store_id,
                    store_name = s.store_name,
                    street = s.street,
                    city = s.city,
                    email = s.email
                });
    
                return Ok(stores);
            }
    
            // GET: api/stores/5
            [ResponseType(typeof(StoreDTO))]
            public IHttpActionResult Getstores(int id)
            {
                stores store = db.stores.Find(id);
                StoreDTO dto = new StoreDTO
                {
                    store_id = store.store_id,
                    store_name = store.store_name,
                    street = store.street,
                    city = store.city,
                    email = store.email
                };
                if (store == null)
                {
                    return NotFound();
                }
    
                return Ok(dto);
            }
    
            // PUT: api/stores/5
            [ResponseType(typeof(void))]
            public IHttpActionResult Putstores(StoreDTO store)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
    
                stores stores1 = new stores
                {
                    store_id = store.store_id,
                    store_name = store.store_name,
                    street = store.street,
                    city = store.city,
                    email = store.email
                };
    
                db.Entry(stores1).State = EntityState.Modified;
    
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!storesExists(store.store_id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return StatusCode(HttpStatusCode.NoContent);
            }
    
            // POST: api/stores
            [ResponseType(typeof(stores))]
            public IHttpActionResult Poststores(StoreDTO store)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
                stores stores1 = new stores
                {
                    store_id = store.store_id,
                    store_name = store.store_name,
                    street = store.street,
                    city = store.city,
                    email = store.email
                };
                db.stores.Add(stores1);
                db.SaveChanges();
    
                return CreatedAtRoute("DefaultApi", new { id = store.store_id }, store);
            }
    
            // DELETE: api/stores/5
            [ResponseType(typeof(StoreDTO))]
            public IHttpActionResult Deletestores(int id)
            {
                stores stores = db.stores.Find(id);
                if (stores == null)
                {
                    return NotFound();
                }
    
                StoreDTO dto = new StoreDTO
                {
                    store_id = stores.store_id,
                    store_name = stores.store_name,
                    street = stores.street,
                    city = stores.city,
                    email = stores.email
                };
    
                db.stores.Remove(stores);
                db.SaveChanges();
    
                return Ok(stores);
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
    
            private bool storesExists(int id)
            {
                return db.stores.Count(e => e.store_id == id) > 0;
            }
        }
    

  2. Dox-chan 1 Reputation point
    2022-03-02T19:50:52.363+00:00

    public class StoreViewController : Controller
    {
    HttpClient client = new HttpClient();
    // GET: StoreView
    public ActionResult Index()
    {
    IEnumerable<StoreDTO> stores = null;

            client.BaseAddress = new Uri("http://localhost:53739/api/");
            var responseTask = client.GetAsync("stores");
            responseTask.Wait();
            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<IList<StoreDTO>>();
                stores = readTask.Result;
            }
    
            return View(stores);
        }
    
        // GET: StoreView/Details/5
        public ActionResult Details(int id)
        {
            StoreDTO store = null;
            client.BaseAddress = new Uri("http://localhost:53739/api/");
            var responseTask = client.GetAsync("stores?id="+id);
            responseTask.Wait();
            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<StoreDTO>();
                store = readTask.Result;
            }
            return View(store);
        }
    
        // GET: StoreView/Create
        public ActionResult Create()
        {
            return View();
        }
    
        // POST: StoreView/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection, StoreDTO store)
        {
            client.BaseAddress = new Uri("http://localhost:53739/api/stores");
            var postTask = client.PostAsJsonAsync("stores", store);
            postTask.Wait();
            var result = postTask.Result;
            if (result.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View();
        }
    
        // GET: StoreView/Edit/5
        public ActionResult Edit(int id)
        {
            StoreDTO store = null;
            client.BaseAddress = new Uri("http://localhost:53739/api/");
            var responseTask = client.GetAsync("stores?id=" + id);
            responseTask.Wait();
            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<StoreDTO>();
                store = readTask.Result;
            }
            return View(store);
        }
    
        // POST: StoreView/Edit/5
        [HttpPost]
        public ActionResult Edit(FormCollection collection, StoreDTO store)
        {
            client.BaseAddress = new Uri("http://localhost:53739/api/stores");
            var putTask = client.PutAsJsonAsync("stores", store);
            putTask.Wait();
            var result = putTask.Result;
            if (result.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View(store);
        }
    
        // GET: StoreView/Delete/5
        public ActionResult Delete(int id)
        {
            StoreDTO store = null;
            client.BaseAddress = new Uri("http://localhost:53739/api/");
            var responseTask = client.GetAsync("stores?id=" + id);
            responseTask.Wait();
            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<StoreDTO>();
                store = readTask.Result;
            }
            return View(store);
        }
    
        // POST: StoreView/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            client.BaseAddress = new Uri("http://localhost:53739/api/");
            var deleteTask = client.DeleteAsync("stores?id="+id);
            deleteTask.Wait();
            var result = deleteTask.Result;
            if (result.IsSuccessStatusCode)
            {
                return RedirectToAction("Index");
            }
            return View(id);
        }
    }
    
    0 comments No comments

  3. Dox-chan 1 Reputation point
    2022-03-02T20:13:13.397+00:00

    This can be useful aswell
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.Description;
    using TestUe.Models;

    namespace TestUe.Controllers
    {
        public class stocksController : ApiController
        {
            private CompanyEntities db = new CompanyEntities();
    
            // GET: api/stocks
            public IHttpActionResult Getstocks(int sid)
            {
                var stocks = db.stocks.Include("products").Where(s => s.store_id == sid).Select(s => new StocksDTO()
                {
                    store_id = s.store_id,
                    product_id = s.product_id,
                    quantity = s.quantity,
                    product_name = s.products.product_name,
                });
                return Ok(stocks);
            }
    
            // GET: api/stocks/5
            [ResponseType(typeof(StocksDTO))]
            public IHttpActionResult Getonestocks(int sId, int pId)
            {
                stocks stocks = db.stocks.Find(sId, pId);
                StocksDTO stdto = new StocksDTO()
                {
                    store_id = stocks.store_id,
                    product_id = stocks.product_id,
                    quantity = stocks.quantity,
                    product_name = stocks.products.product_name
                };
                if (stocks == null)
                {
                    return NotFound();
                }
    
                return Ok(stdto);
            }
    
            // PUT: api/stocks/5
            [ResponseType(typeof(void))]
            public IHttpActionResult Putstocks(StocksDTO stocks)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                stocks st = new stocks()
                {
                    store_id = stocks.store_id,
                    product_id = stocks.product_id,
                    quantity = stocks.quantity
                };
                db.Entry(st).State = EntityState.Modified;
    
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!stocksExists(stocks.product_id, stocks.store_id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return StatusCode(HttpStatusCode.NoContent);
            }
    
            // POST: api/stocks
            [ResponseType(typeof(StocksDTO))]
            public IHttpActionResult Poststocks(StocksDTO stocks)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                stocks st = new stocks()
                {
                    store_id = stocks.store_id,
                    product_id = stocks.product_id,
                    quantity = stocks.quantity
                };
                db.stocks.Add(st);
    
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateException)
                {
                    if (stocksExists(stocks.store_id, stocks.product_id))
                    {
                        return Conflict();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return CreatedAtRoute("DefaultApi", new { id = stocks.store_id }, stocks);
            }
    
            // DELETE: api/stocks/5
            [ResponseType(typeof(StocksDTO))]
            public IHttpActionResult Deletestocks(int sId, int pId)
            {
                stocks stocks = db.stocks.Find(sId, pId);
                if (stocks == null)
                {
                    return NotFound();
                }
                StocksDTO stdto = new StocksDTO()
                {
                    store_id = stocks.store_id,
                    product_id = stocks.product_id,
                    quantity = stocks.quantity,
                    product_name = stocks.products.product_name
                };
                db.stocks.Remove(stocks);
                db.SaveChanges();
    
                return Ok(stdto);
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
    
            private bool stocksExists(int pId, int sId)
            {
                return db.stocks.Count(e => e.store_id == sId && e.product_id == pId) > 0;
            }
        }
    }
    
    0 comments No comments