Saturday, June 2, 2018

Make a new "API controller" in .NET Core 2.

Right-click on the Controllers folder and pick Add > New Item... ...and pick Web API Controller Class from the ASP.NET Core options or the Web options within the ASP.NET Core options or the ASP.NET options within the Web options within the ASP.NET Core options to make something like so:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
 
// For more information on enabling Web API for empty projects, visit
      https://go.microsoft.com/fwlink/?LinkID=397860

 
namespace Pasta.Controllers
{
   [Route("api/[controller]")]
   public class SpaghettiController : Controller
   {
      
// GET: api/values
      [HttpGet]
      public IEnumerable<string> Get()
      {
         return new string[] { "value1", "value2" };
      }
      
      
// GET api/values/5
      [HttpGet("{id}")]
      public string Get(int id)
      {
         return "value";
      }
      
      
// POST api/values
      [HttpPost]
      public void Post([FromBody]string value)
      {
      }
      
      
// PUT api/values/5
      [HttpPut("{id}")]
      public void Put(int id, [FromBody]string value)
      {
      }
      
      
// DELETE api/values/5
      [HttpDelete("{id}")]
      public void Delete(int id)
      {
      }
   }
}

 
 

Note that our class is inheriting from Controller and not ApiController. There are no ApiControllers anymore in modern MVC like there were in MVC 4 and MVC 5. Instead there is just Controller to inherit from and whether or not it, our child of Controller, serves up JSON or a view depends on what we put inside. Pages 78 and 79 of "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis have us making such a controller, but the controller has one method which starts out like this:

[HttpGet("Latest/{num}")]
public IActionResult Latest(int num = 10)
{

 
 

...and ends like so:

return new JsonResult(
   sampleQuizzes,
   new JsonSerializerSettings()
   {
      Formatting = Formatting.Indented
   }
);

 
 

sampleQuizzes is a collection to be returned and the second argument denotes how to serialize the collection. The using Newtonsoft.Json; using declaration loops in the ability to serialize JSON in this manner.

No comments:

Post a Comment