Blog for Junior Developers C#/.NET

Friday, November 08, 2024

ASP.NET Core MVC has huge possibilities. We can write various applications here. Both small, own web programs, as well as large applications used by many clients. So it is a technology that is and will continue to be used in many companies. When creating such applications, it is worth following the best practices, so that the applications are optimal, fast and, above all, user-friendly. In this article, I will present you with 12 best programming practices in ASP.NET Core MVC, thanks to which your application will be even better.

12-best-practices-in-aspdotnet-core-mvc.jpg

1. Use LibMan to manage client-side libraries


In an ASP.NET Core application, we always use various client-side JavaScript libraries. The easiest way to manage them is with the LibMan library, which allows us to fully configure all packages. Then we keep all information about client-side libraries in the libman.json file and we can easily add a new library, change the version, or remove it from our project.


2. The Program.cs class should be concise and readable


In .NET 6, the Program.cs class contains the code for starting the application and all the configuration of our application. Among other things, this class is also where we register and configure our services (before .NET 6, this configuration was still in the startup class). This class can become very extensive over time, there can be a lot of configurations here, a lot of lines of code, so it is a good practice to separate this logic out, and the easiest way to do this is to use extension methods. By using extension methods here, the Program.cs class will be smaller, which makes it more readable.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);

var app = builder.Build();

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();


3. Implement global error handling


It is worth implementing global exception handling in your application, thanks to which you will catch all unexpected exceptions that were thrown in the application. In ASP.NET Core you can implement global exception handling, e.g. using Middleware. Of course, it is worth saving all detailed information about the error, e.g. to a file along with additional information about the request, thanks to which it will be easier for you to diagnose this error. Then it is worth displaying a nice view of the error to the user, not necessarily with detailed information, some general message will be enough here. The user does not need to know exactly what went wrong, and you should especially not return the entire stack trace of the error here.

app.UseMiddleware<ExceptionHandlerMiddleware>();


4. Use client-side and server-side validation


Validation of data entered into the application should be mandatory. In ASP.NET Core MVC, we can use both client-side and server-side validation. It is worth adding both validations to the application. If you have client-side validations, the data will be validated in the browser and only when they are correct will they be sent to the server. To create validation conditions, you can use DataAnnotation or FluentValidation. However, to unlock client-side validation using DataAnnotation, just add a reference to _ValidationScriptsPartial.cshtml to the view.

[Required(ErrorMessage = "Field 'StartDate' is required")]
public DateTime StartDate { get; set; }

_ValidationScriptsPartial.cshtml

<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>


5. Use components and partial views


When creating razor views, we often have some part of the code, part of the HTML, that repeats itself in different views. Instead of creating or copying all this code in these views, it is much easier to use components or partial views in these places, depending on what we want to achieve in this case. By exporting this part of the code to a component or partial view, our main view has less code, which also makes it more readable. Instead of calling a dozen or so lines of code, it is enough to call one line. So we do not have repeating code in different views. It is easier for us to manage this code in one place. If in the future it turns out that we need to make some change to this code, then it is enough to change it in only one place, we will not have to update a lot of views. So this solution has only advantages.

public class MainViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(string priority)
    {
        return View();
    }
}

<vc:mainpriority="2" />

<partial name="_ValidationScriptsPartial" />


6. If you have repetitive scripts in JS, then separate them to a separate file


The same situation also applies to scripts in JavaScript. If you need a function in JavaScript that, for example, shortens a string to 20 characters, then do not define it every time in the Razor view, where you need to use it. A much better solution will be to add a script, e.g. with string extensions, place this script in this external script and add a reference to this script in the view where we need to use it. This will save us a lot of time and lines of code. Just like before, if you want to make a change to any common function, then all you have to do is enter it in one place.

<script src="~/js/stringextensions.js"></script>


7. Use separate configuration files for different environments


In ASP.NET Core, we can have multiple appsettings.json configuration files. This means we can create a separate configuration file for production and development. Depending on how many different environments we have to run our application, we can create as many different configuration files and it is worth using this mechanism. It is much more practical than constantly changing or deleting these entries in one file. You can store, for example, connection data to the production and development database in these configuration files and easily switch between these environments at any time. To do this, simply add the name of the environment after appsettings, e.g. appsettings.development.json, appsettings.staging.json, etc. and run accordingly.

appsettings.json

{
    "ConnectionStrings": {
        "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*",
    "TemplateKey": "Basic"
}


appsettings.Development.json

{
    "ConnectionStrings": {
        "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
    }
}


8. Use asynchronous code


If you have the opportunity, try to use asynchronous code. This can improve the performance and responsiveness of your application. Although your query will not execute faster, we will not block the thread and the application will be able to perform other requests. If you want your method to be asynchronous, you must use the async keyword in its signature, return Task, and in the place where you call code that takes longer to execute, use the await keyword.

public async Task<IActionResult> Client()
{
    return View(await Mediator.Send(new GetClientQuery()));
}


9. Use ajax when you want to change data without refreshing the entire page


When you need to execute a command, refresh some data, you can do it in ASP.NET Core MVC without re-rendering the entire page. To do this, you should use ajax. Such a call will definitely improve the UX of our application. Calling ajax is very simple, just add a short script and the appropriate action in the controller. Also remember to properly secure any possible errors.

$.ajax({
    type: "POST",
    url: "/Ticket/Add",
    data: {
        id: id
    },
    success: function (data) {
    },
    error: function (data) {
    },
    dataType: 'json'
});


10. Display a spinner when loading pages


If you are executing a command on the page that takes a long time, or you are loading some data, it is worth displaying a so-called spinner to the user, i.e. a spinning circle that informs that operations are being performed in the application. It can also be some kind of progress bar. Thanks to this, the user will know that they have to wait a moment for the data to load and will not have the impression that the application has hung. This is another thing that you can use to improve the UX in your application. Thanks to such a detail, users will definitely work better on your application.


11. Place your application on fast servers


There is nothing worse than placing your application on weak servers or hosting. This can cause both your database queries and the entire application to run very slowly. Sometimes it can even make you wait a few seconds for a response from the server. This is very frustrating. You probably don't want to focus on optimizing the speed of your application, and after deploying it to the server, still have a slow-running application. I don't want to be anti-advertising for some companies where I tested hosting, but I admit that I have also come across such hosting, which sometimes made the application work fine, and sometimes it was impossible to work on it. So if you have some key, money-making applications, where speed is important, invest in a good server. You can make your application available, for example, in the Azure cloud.


12. Test your application


Finally, I can't help but mention testing your application. I mean manual and automated tests. Nothing irritates the end user more than bugs in the application. If you stick to good design patterns, write clean code, then writing automated tests for applications written in ASP.NET Core MVC is easy. It's worth writing unit and integration tests, your users will definitely thank you for the smallest possible number of errors in the application. Every new functionality in your application should be thoroughly tested.


ASP.NET Core School


If you are interested in topics related to creating professional web applications in ASP.NET Core, consider joining: ASP.NET Core School. This is an advanced, practical ASP.NET Core MVC + REST API training for C#/.NET Developers. The training consists of 14 extensive modules. In the training, we create a complete application in ASP.NET Core from the first lines of code to cloud implementation (more here).

Author of the article:
Kazimierz Szpin

KAZIMIERZ SZPIN
Software Developer C#/.NET, Freelancer. Specializes in ASP.NET Core, ASP.NET MVC, ASP.NET Web API, Blazor, WPF and Windows Forms.
Author of the blog CodeWithKazik.com

Previous article - 8 Common ASP.NET Core Beginner Mistakes
Dodaj komentarz
© Copyright 2024 CodeWithKazik.com. All rights reserved. Privacy policy.
Design by Code With Kazik and Modest Programmer.