Wednesday 27 January 2021

Part 11: MVC Configuration in Asp.Net Core 3.1

In this article I will show you how to configure MVC in asp.net core 3.1 using Empty project template. I’m using asp.net core 3.1 project created in part 10.  Code available on GitHub.

Create folder with name Controllers under project root directory.

Make sure you updated in configure method of Startup class shown below.


Make sure UseStaticFiles middleware come before UseRouting middleware. If any static file(image, Html, etc) requested then UseStaticFiles serve and short circuit the request. For Controller with action name, it will pass request to UseRouting middleware.

UseRouting middleware used to verify/Check requested route in already configured route or we can say validate incoming route with already configured route and actual execution of requested route performed by UseEndpoints middleware.

 

Create controller with index action in controller folder shown below. Right click on controllers folder select Add option and then controller.

Select Empty controller highlighted above and click on add button.

HomeController gets added in Controllers folder, now modify action method code highlighted below.

Now run application and check, error encountered at UseEndpoints middleware.


As we discussed UseEndPoints middleware execute requested route and based on error description, required services not configured. Stop application and configure required services in ConfigureService method.

 


 Run application and check browser.



Create view for Index action method, right click on Index action method and select Add razor view.


Index view gets created under Views folder.



Now run application and check result om browser window, and error occurred with message service needs to register to do the operation.



 

To fix this go to Startup.cs file and Add razer page service shown below.




But later we require Json formatters, CORS,.. etc. Its better rather adding multiple services, add one main service which contains all these service call(AddMvcCore, AddRazorPages, …etc).


Previous                                                                                                                                                 Next


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home