Write and expose an ASP.NET Core API in Sitecore MVP Project

The ASP.NET Core API is the backbone for headless concept. So, the basics deserve a blog article.

Since a picture is better than a thousand words, added two pictures to  summarise this blog!


In case of the Sitecore MVP project, an entry in StarupExtensions.cs is mandatory to expose the controller method! 

Note that the methods in StartupExtensions.cs need to be invoked from Startup.cs in turn and the idea of Configure method in Startup.cs is to build the application by  implementing the IApplicationBuilder interface to which StartupExtensions.cs is one where endpoints are registered!

This blog article uses the Sitecore MVP project as example and specifically utilises the ApplicationController, which is part of MVP.Feature.Forms.Rendering .NET Core project:




Create and invoke a method without Parameters

1. Add an endpoint in ApplicationController.cs under MVP.Feature.Forms.Rendering project:

 [HttpGet]

  public IActionResult GetMyInfo()

 {            

         return Json(new { greetings = "hi"});

 }


2. Then add an entry in the StartupExtensions.cs:

endpoints.MapControllerRoute(

                     name: "getmyInfo",

                     pattern: "application/getmyinfo",

                     new { controller = "Application", action = "GetMyInfo" }

                );


3. That's it, access the endpoint from the browser:



Create and invoke a method with Parameters

Same as above but pattern is important in this case.  

1. Since this is an example, modify the same endpoint in ApplicationController.cs under MVP.Feature.Forms.Rendering project:

 [HttpGet]

  public IActionResult GetMyInfo(string msg)

 {            

         return Json(new { greetings = msg});

 }

2. Then add an entry in the StartupExtensions.cs:

endpoints.MapControllerRoute(

                     name: "getmyInfo",

                     pattern: "application/getmyinfo/{msg}",

                     new { controller = "Application", action = "GetMyInfo" }

                );

3. That's it, access the endpoint from the browser by passing the parameter as part of the url:


Now, the options are limitless,  you can now call a Sitecore api to fetch content items by passing this parameter, process the data and send it back to the front-end!

Comments

Popular Posts