Implementing BaseApiController

The next thing to do is to derive the QuizController, QuestionController, AnswerController, and ResultController from this BaseApiController class, so they can inherit the shared properties and get rid of a lot of duplicate code; let's start with the QuizController.

Open the QuizController.cs file and perform the following changes (updated lines are highlighted):

[...]

namespace TestMakerFreeWebApp.Controllers
{
public class QuizController : BaseApiController
{
#region Constructor
public QuizController(ApplicationDbContext context)
: base(context) { }
#endregion

[...]

As we can see, we removed the following:

  • The [Route("api/[controller]")] attribute, since it's already present in the BaseApiController; all the Base class attributes will be inherited by the derived classes as well
  • The Private Members region, thus shrinking the constructor to a minimal amount

Once done, scroll down to the end of the Get(id) action method and update its return value in the following way (updated lines are highlighted):

[...]        

return new JsonResult(
quiz.Adapt<QuizViewModel>(),
JsonSettings);

[...]

Replace all the other JsonSerializerSettings() instances created on the fly with the JsonSettings property to further reduce the amount of source code lines.

Once done with the QuizController, we need to perform these two changes on all the other Web API controllers as well--QuestionController, AnswerController, and ResultController--all except HomeController. For obvious space reasons, we won't do that here, leaving such a task to the reader; the things to do are identical anyway.

IMPORTANT: Ensure not to inherit the BaseApiController class within your HomeController, as this is not a web API Controller; it has its specific set of server-side routing rules to serve the start page; doing that will prevent your app from running properly.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.212.71