European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core Hosting :: ASP.NET Core 2.0 Structured Logging

clock December 15, 2020 07:28 by author Peter

In this tutorial, I will show you how to work with structured logging in ASP.NET Core and Serilog. Let's start with logging, add NuGet packages:
    Serilog.AspNetCore
    Serilog.Sinks.Literate
    Serilog.Sinks.Seq


In Program.cs, configure Serilog using its LoggerConfiguration class and storing an instance of ILogger (returned by CreateLogger) in Serilog’s static Log class.
    public static void Main(string[] args)  
          {  
              Log.Logger = new LoggerConfiguration()  
                          .WriteTo.LiterateConsole()  
                          .CreateLogger();  
      
             BuildWebHost(args).Run();  
          }  
      
          public static IWebHost BuildWebHost(string[] args) =>  
              WebHost.CreateDefaultBuilder(args)  
                  .UseStartup<Startup>()  
                  .UseSerilog()  
                  .Build();  


Using the ILogger is the same process as described in our previous post, however, with Serilog we can do structured logging.
    public async Task Invoke(HttpContext context)  
        {  
            var message = new  
            {  
                GreetingTo = "James Bond",  
                GreetingTime = "Morning",  
                GreetingType = "Good"  
            };  
            this.logger.LogInformation("Inoke executing {@message}", message);  
      
            await context.Response.WriteAsync("Hello Logging!");  
      
            this.logger.LogInformation(  
                "Inoke executed by {developer} at {time}", "Tahir", DateTime.Now);  
        }

Running the application will show messages in Console window.

Structured logging is a technique to include semantic information as part of the messages being logged. This helps ‘machine readability’ of these messages and tools can be written to analyze raw log messages and produce interesting information.

Serilog uses message template, similar to string.Format() in .NET. Few interesting aspects of template syntax are,
    Use {} to enclose property names e.g. {developer} in above solution. These will be stored as metadata and can be queried using structured data storage (e.g. Seq, Azure).
    Use @ to preserve object structure e.g. in solution above the anonymous object is serialized into JSON representation.

Enrichers
In Serilog, enrichers are used to attach information to every log event that can then be used by structured data storage (e.g. Seq, Azure) for viewing and filtering. A simple way to do this is by using .Enrich.WithProperty() when configuring Serilog,
    Log.Logger = new LoggerConfiguration()  
                               .Enrich.WithProperty("ApiVersion", "1.2.5000")  
                               .WriteTo.LiterateConsole()  
                               .CreateLogger();  
As we saw in the previous post, a category can be attached to the logged messages, which normally is the fully qualified name of the class. This information could be used by structured data storage (e.g. Seq, Azure). Serilog provides this mechanism by attaching Context via ForContext() method,
    Log.Logger = new LoggerConfiguration()  
                        .Enrich.WithProperty("ApiVersion", "1.2.5000")  
                        .WriteTo.LiterateConsole()  
                        .CreateLogger()  
                        .ForContext<HelloLoggingMiddleware>();  


Sinks
Sinks in Serilog refer to destination of log messages e.g. file, database or console (in our example). There are several sinks available (refer to link below). I’ll use Seq as an example sink to show how all the metadata we’ve added is available in a structured storage,
    Log.Logger = new LoggerConfiguration()  
                              .Enrich.WithProperty("ApiVersion", "1.2.5000")  
                              .WriteTo.LiterateConsole()  
                              .WriteTo.Seq("http://localhost:5341")  
                              .CreateLogger()  
                              .ForContext<HelloLoggingMiddleware>(); 

Notice how data we added via enricher, context and custom object appears as key/value pairs. This can now be used for filtering data and creating dashboards within Seq.



European ASP.NET Core Hosting :: How to Write Testable Code in .NET?

clock December 8, 2020 08:15 by author Peter

In this article, I give a brief introduction to writing testable code. Although I have described and used samples in the context of .NET, the high-level principles of writing testable code applies to most of the programming language.  
 
What is Testable Code?
Testable code refers to the loosely coupled code where code does not directly depend on internal/external dependencies, so we can easily replace the real dependencies (sometimes referred to as real service) with mock services in test cases. For example, if my code calls a method GetProductInfo() which is connecting to a real database, fetching the product information, and returning to the main method. To test my main method functionality without actually connecting to the real database, I can write a test that uses a mock service to get product data.
 
While it might seem a little confusing at this point, it is actually very simple when you see a working example of it.
 
Why is it important to write testable code?
Writing testable code is crucial, as it helps you to identify and resolve the potential problems/ bugs in the early development stage instead of getting issues in UAT or production when working with real services. Also, testing the fake services is fast compared to testing real services. For example, connecting to a real database is more time consuming than testing with fake data in mock service.
 
How to write testable code
Writing testable code is all about dependency management. If we are writing code using the SOLID principles, then our code will already be loosely coupled and in compliance with testing standards. While writing testable code, our main objective is to identify the dependencies and moving the instantiation of those dependencies outside of our code. When we create an object of the class using a new keyword inside the current class, then this class directly depends on the class whose object we are creating. For example, in the below code ProcessProduct class creating the object of DBService class. Hence DBService class is the dependency and ProcessProduct class depends directly on DBService.
    class Product  
        {  
            public int Id { get; set; }  
            public string Name { get; set; }  
            public string Category { get; set; }  
            public float Price { get; set; }  
      
        }  
        class ProcessProduct  
        {  
            public void DisplayProduct()  
            {  
                DBService dbService = new DBService();  
                var product = dBService.getProduct();  
                Console.WriteLine($" Product Name: { product.Name } Category: { product.Category } Price: { product.Price }");  
            }  
              
        }  
      
        class DBService  
        {  
            public Product getProduct() {  
                throw new NotImplementedException("Get product from database");  
            }  
        }  


To make this code loosely coupled, we will use a very popular design pattern called dependency injection. There are several ways to implement dependency injection which is itself a very wide topic. So to keep this article simple, I will use one of the ways to implement dependency injection-  Dependency injection using Constructor.
 
In this method, instead of creating the object of DBService inside ProcessProduct, we will inject the object through the constructor of the dependent class and save it in a private variable as shown in the below code:
    class Product  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public string Category { get; set; }  
        public float Price { get; set; }  
      
    }  
    class ProcessProduct  
    {  
        private IDBservice _dbService;  
      
        public ProcessProduct(IDBservice dbService)  
        {  
            _dbService = dbService;  
        }  
        public void DisplayProduct()  
        {  
            var product = _dbService.getProduct();  
            Console.WriteLine($" Product Name: { product.Name } Category: { product.Category } Price: { product.Price }");  
        }  
          
    }  
      
    interface IDBservice {  
         Product getProduct();  
    }  
      
    class DBService : IDBservice  
    {  
        public Product getProduct() {  
            throw new NotImplementedException("Get product from database");  
        }  
    }  


We have also created an interface IDBService in the above example and declared the object of DBService using this interface. By using this interface, we allow any class’object that implements the IDBService interface to inject through the constructor.
 
Below is an example of passing a mock class object for testing.
    class ProcessProduct  
        {  
            private IDBservice _dbService;  
      
            public ProcessProduct(IDBservice dbService)  
            {  
                _dbService = dbService;  
            }  
            public void DisplayProduct()  
            {  
                var product = _dbService.getProduct();  
                Console.WriteLine($" Product Name: { product.Name } Category: { product.Category } Price:  { product.Price }");  
            }  
      
        }  
      
        interface IDBservice {  
            Product getProduct();  
        }  
      
        class MockDBService : IDBservice  
        {  
            public Product getProduct()  
            {  
                return new Product()  
                {  
                    Id = 2124,  
                    Name = "Eggs",  
                    Category = "Food",  
                    Price = 2.23m  
                };  
      
            }  
      
        }  
      
        class TestProcessProduct  
        {  
            void Test()  
            {  
                ProcessProduct processProduct = new ProcessProduct(new MockDBService());  
                processProduct.DisplayProduct();  
            }  
        }  


In this example, we want to test the ProcessProduct class to display product information without actually connecting to the real database. To achieve this, instead of injecting the DBService class object we are injecting the MockDBService class object. And because of dependency injection, we do not need to do any changes in the ProcessProduct class. Hence, this code is loosely coupled and testable.

 



ASP.NET Core 3.1.9 Hosting - HostForLIFE.eu :: Converting HTML to Plain Text in ASP.NET

clock December 1, 2020 08:40 by author Peter

Sometimes you want to remove tags from HTML and get only plain text. In general, this is simple task but there are few drawbacks in some scenarios. The simplest solution is to just remove all tags from given HTML without any formatting.

You can do it with code like this:

[ C# ]

public string RemoveHTMLTags(string HTMLCode)
{
 return System.Text.RegularExpressions.Regex.Replace(
   HTMLCode, "<[^>]*>", "");
}

[ VB.NET ]

Public Function RemoveHTMLTags(ByVal HTMLCode As String) As String
 Return System.Text.RegularExpressions.Regex.Replace( _
   HTMLCode, "<[^>]*>", "")
End Function

Better HTML to plain text conversion\

Example above removes any tag from HTML. This is good enough in some scenarios, but there are some issues too:

- Text inside HEAD tag will be visible too
- Empty spaces &nbsp; and new lines <br /> or paragraph <p> will be lost
- Unwanted empty spaces that are invisible in HTML will show in plain text, and that will distract text even more
- Special characters like &amp; or &copy etc. will not be translated etc

To solve all these problems, you need a little more processing of input HTML. Next function will provide better HTML to text conversion:

[ C# ]

// This function converts HTML code to plain text
// Any step is commented to explain it better
// You can change or remove unnecessary parts to suite your needs

public string HTMLToText(string HTMLCode)
{
 // Remove new lines since they are not visible in HTML
 HTMLCode = HTMLCode.Replace("\n", " ");

 
 // Remove tab spaces
 HTMLCode = HTMLCode.Replace("\t", " ");
 
 // Remove multiple white spaces from HTML
 HTMLCode = Regex.Replace(HTMLCode, "\\s+", " ");
 
 // Remove HEAD tag
 HTMLCode = Regex.Replace(HTMLCode, "<head.*?</head>", ""
                     , RegexOptions.IgnoreCase | RegexOptions.Singleline);

 
 // Remove any JavaScript
 HTMLCode = Regex.Replace(HTMLCode, "<script.*?</script>", ""
   , RegexOptions.IgnoreCase | RegexOptions.Singleline);

 
 // Replace special characters like &, <, >, " etc.
 StringBuilder sbHTML = new StringBuilder(HTMLCode);

// Note: There are many more special characters, these are just
// most common. You can add new characters in this arrays if needed
 string[] OldWords = {"&nbsp;", "&amp;", "&quot;", "&lt;",
   "&gt;", "&reg;", "&copy;", "&bull;", "&trade;"};
 string[] NewWords = {" ", "&", "\"", "<", ">", "®", "©", "•", "â„¢"};
 for(int i = 0; i < OldWords.Length; i++)
 {
   sbHTML.Replace(OldWords[i], NewWords[i]);
 }

 
 // Check if there are line breaks (<br>) or paragraph (<p>)
 sbHTML.Replace("<br>", "\n<br>");
 sbHTML.Replace("<br ", "\n<br ");
 sbHTML.Replace("<p ", "\n<p ");

 
 // Finally, remove all HTML tags and return plain text
 return System.Text.RegularExpressions.Regex.Replace(
   sbHTML.ToString(), "<[^>]*>", "");
}

[ VB.NET ]

' This function converts HTML code to plain text
' Any step is commented to explain it better
' You can change or remove unnecessary parts to suite your needs

Public Function HTMLToText(ByVal HTMLCode As String) As String
 ' Remove new lines since they are not visible in HTML
 HTMLCode = HTMLCode.Replace("\n", " ")
 
 ' Remove tab spaces
 HTMLCode = HTMLCode.Replace("\t", " ")
 
 ' Remove multiple white spaces from HTML
 HTMLCode = Regex.Replace(HTMLCode, "\\s+", "  ")
 
 ' Remove HEAD tag
 HTMLCode = Regex.Replace(HTMLCode, "<head.*?</head>", "" _
   , RegexOptions.IgnoreCase Or RegexOptions.Singleline)

 
 ' Remove any JavaScript
 HTMLCode = Regex.Replace(HTMLCode, "<script.*?</script>", "" _
   , RegexOptions.IgnoreCase Or RegexOptions.Singleline)
 

 ' Replace special characters like &, <, >, " etc.
 Dim sbHTML As StringBuilder = New StringBuilder(HTMLCode)

 ' Note: There are many more special characters, these are just
 ' most common. You can add new characters in this arrays if needed

 Dim OldWords() As String = {"&nbsp;", "&amp;", "&quot;", "&lt;", _
    "&gt;", "&reg;", "&copy;", "&bull;", "&trade;"}
 Dim NewWords() As String = {" ", "&", """", "<", ">", "®", "©", "•", "â„¢"}
 For i As Integer = 0 To i < OldWords.Length
   sbHTML.Replace(OldWords(i), NewWords(i))
 Next i

 
 ' Check if there are line breaks (<br>) or paragraph (<p>)
 sbHTML.Replace("<br>", "\n<br>")
 sbHTML.Replace("<br ", "\n<br ")
 sbHTML.Replace("<p ", "\n<p ")

 
 ' Finally, remove all HTML tags and return plain text
 Return System.Text.RegularExpressions.Regex.Replace( _
    sbHTML.ToString(), "<[^>]*>", "")
End Function

HTML to plain text ASP.NET example

Now, you can build an example that convert HTML to plain text. Create new web page with one Button control and two TextBox controls, like on image bellow:

First TextBox control ID will be tbHTML and second TextBox control ID set to tbPlainText. On button's click write this code:

[ C# ]

protected void btnTextToHTML_Click(object sender, EventArgs e)
{
 tbPlainText.Text = HTMLToText(tbHTML.Text);
}


[ VB.NET ]

Protected Sub btnTextToHTML_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTextToHTML.Click
 tbPlainText.Text = HTMLToText(tbHTML.Text)
End Sub

Please note that HTML is considered as dangerous input. To make this example works you need to add ValidateRequest="false" part to @Page directive. Otherwise, you'll get an error "A potentially dangerous Request.Form value was detected from the client...)" like on next image.

 

When you set ValidateRequest parameter to false, you can run an example. Place some HTML code to tbHTML TextBox control and click on Button. Plain text will be extracted from given HTML and shown in tbPlainText.

As you see, there are few different options when converting HTML to plain text. Depending of your needs you can only remove tags or provide additional formatting. Suggested HTMLToText function is not perfect. You can make it better if you add all symbols or add line breaks for new table rows, or add tab spaces for evey new table cell etc. Be aware that with every new option included this function becomes slower. If you overdo the conversion could be unsatisfactory, especially if you have large HTML files. Happy coding!

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET Core Hosting :: Remoting in .NET

clock November 24, 2020 08:30 by author Peter

Distributed computing is an integral part of almost every software development. Before .Net Remoting, DCOM was the most used method of developing distributed application on Microsoft platform. Because of object oriented architecture, .NET Remoting replaces DCOM as .Net framework replaces COM.
 
Benefits of Distributed Application Development
 
Fault Tolerance: Fault tolerance means that a system should be resilient when failures within the system occur.
 
Scalability: Scalability is the ability of a system to handle increased load with only an incremental change in performance.
 
Administration: Managing the system from one place.
 
In brief, .NET remoting is an architecture which enables communication between different application domains or processes using different transportation protocols, serialization formats, object lifetime schemes, and modes of object creation. Remote means any object which executes outside the application domain. The two processes can exist on the same computer or on two computers connected by a LAN or the Internet. This is called marshalling (This is the process of passing parameters from one context to another.), and there are two basic ways to marshal an object:
 
Marshal by value: the server creates a copy of the object passes the copy to the client.
 
Marshal by reference: the client creates a proxy for the object and then uses the proxy to access the object.
 
Comparison between .NET Remoting and Web services


Architecture

Remote objects are accessed thro channels. Channels are Transport protocols for passing the messages between Remote objects. A channel is an object that makes communication between a client and a remote object, across app domain boundaries. The .NET Framework implements two default channel classes, as follows:
 
HttpChannel: Implements a channel that uses the HTTP protocol. TcpChannel: Implements a channel that uses the TCP protocol (Transmission Control Protocol). Channel take stream of data and creates package for a transport protocol and sends to other machine. A simple architecture of .NET remoting is as in Fig 1.


As Fig.1 shows, Remoting system creates a proxy for the server object and a reference to the proxy will be returned to the client. When client calls a method, Remoting system sends request thro the channel to the server. Then client receives the response sent by the server process thro the proxy.
 
Example
Let us see a simple example which demonstrates .Net Remoting. In This example the Remoting object will send us the maximum of the two integer numbers sent.
Creating Remote Server and the Service classes on Machine 1: Please note for Remoting support your service (Remote object) should be derived from MarshalByRefObject.
    using System;  
    using System.Runtime.Remoting.Channels; //To support and handle Channel and channel sinks  
    using System.Runtime.Remoting;  
    using System.Runtime.Remoting.Channels.Http; //For HTTP channel  
    using System.IO;  
    namespace ServerApp {  
      public class RemotingServer {  
        public RemotingServer() {  
          //  
          // TODO: Add constructor logic here  
          //  
        }  
      }  
      //Service class  
      public class Service: MarshalByRefObject {  
        public void WriteMessage(int num1, int num2) {  
          Console.WriteLine(Math.Max(num1, num2));  
        }  
      }  
      //Server Class  
      public class Server {  
        public static void Main() {  
          HttpChannel channel = new HttpChannel(8001); //Create a new channel  
          ChannelServices.RegisterChannel(channel); //Register channel  
          RemotingConfiguration.RegisterWellKnownServiceType(typeof Service), "Service", WellKnownObjectMode.Singleton);  
        Console.WriteLine("Server ON at port number:8001");  
        Console.WriteLine("Please press enter to stop the server.");  
        Console.ReadLine();  
      }  
    }  
    }


Save the above file as ServerApp.cs. Create an executable by using Visual Studio.Net command prompt by, csc /r:system.runtime.remoting.dll /r:system.dll ServerApp.cs
 
A ServerApp.Exe will be generated in the Class folder.
 
Run the ServerApp.Exe will give below message on the console
 
Server ON at port number:8001
 
Please press enter to stop the server.
 
In order to check whether the HTTP channel is binded to the port, type http://localhost:8001/Service?WSDL in the browser. You should see a XML file describing the Service class.
 
Please note before running above URL on the browser your server (ServerApp.Exe should be running) should be ON.
 
Creating Proxy and the Client application on Machine 2
 
SoapSuds.exe is a utility which can be used for creating a proxy dll.
 
Type below command on Visual studio.Net command prompt.
 
soapsuds -url:http://< Machine Name where service is running>:8001/Service?WSDL -oa:Server.dll
 
This will generates a proxy dll by name Server.dll. This will be used to access remote object.
 
Client Code
    using System;  
    using System.Runtime.Remoting.Channels; //To support and handle Channel and channel sinks  
    using System.Runtime.Remoting;  
    using System.Runtime.Remoting.Channels.Http; //For HTTP channel  
    using System.IO;  
    using ServerApp;  
    namespace RemotingApp {  
      public class ClientApp {  
        public ClientApp() {}  
        public static void Main(string[] args) {  
          HttpChannel channel = new HttpChannel(8002); //Create a new channel  
          ChannelServices.RegisterChannel(channel); //Register the channel  
          //Create Service class object  
          Service svc = (Service) Activator.GetObject(typeof(Service), "http://<Machine name where Service running>:8001/Service"); //Localhost can be replaced by  
          //Pass Message  
          svc.WriteMessage(10, 20);  
        }  
      }  
    }


Save the above file as ClientApp.cs. Create an executable by using Visual Studio.Net command prompt by, csc /r:system.runtime.remoting.dll /r:system.dll ClientrApp.cs
 
A ClientApp.Exe will be generated in the Class folder. Run ClientApp.Exe , we can see the result on Running ServerApp.EXE command prompt.
 
In the same way we can implement it for TCP channel also.



ASP.NET Core 3.1.9 Hosting - HostForLIFE.eu :: Implement Global Exception Handling In ASP.NET Core Application

clock November 17, 2020 07:55 by author Peter

Today, in this article we will discuss the exception handling concept in any ASP.NET Core application. Exception handling is one of the most import functionality or part for any type of application which always need to be taken care and implement properly. Exceptions are mainly means for the run time errors which occur during the execution time of the application. So, if this type of error is not properly handled, then the application will be terminated.

In ASP.NET Core, the concept of exception handling has been changed, and rather to say, now it is in very much in better shape to implement exception handling. For any API projects implementing exception handling against every action, the method is quite time-consuming and it also requires extra efforts. So, for this purpose, we can implement the Global Exception handler so that all types of unhandled exceptions can be caught in this handler. The benefit of implementing a global exception handler is that we need to define this in one place. Through this handler, any exception that occurs in our application will be handled, even we ann new methods or controllers. So, in this article, we will discuss how to implement global exception handling in the ASP.NET Core Web API.

Create ASP.NET Core Web API Projects in Visual Studio 2019
So, before going to discuss the global exception handler, first, we need to create an ASP.NET Web API project. For this purpose, follow the steps mentioned below,

Now open the Microsoft Visual Studio and Click on Create a New Project
In the Create New Project dialog box, select ASP.NET Core Web Application for C# and then click on the Next Button.

In the Configure your new project window, provide the project name and then click on the Create button.
In the Create a New ASP.NET Core Web Application dialog, select API, and then click on Create Button.
Ensure that the checkboxes “Enable Docker Support” and “Configure for HTTPS” are unchecked. We won’t be using these features.
Ensure that “No Authentication” is selected as we won’t be using authentication either.
Click OK

Use the UseExceptionHandler middleware in ASP.NET Core

So, to implement the global exception handler, we can use the benefits of the ASP.NET Core build-in Middleware. A middleware is indicated as a software component inserted into the request processing pipeline which handles the requests and responses. We can use the ASP.NET Core in-build middleware UseExceptionHandler to use as a global exception handler. The ASP.NET Core request processing pipeline includes a chain of middleware components. This pipeline in turn contains a series of request delegates that are invoked one after another. While the incoming requests flow through each of the middleware components in the pipeline, each of these components can either process the request or pass the request to the next component in the pipeline.

Through this middleware, we can get all the detailed information of the exception object like the Stack trace, inner exception, message, etc., and also return that information through the API to return as an output. We need to put the exception handler middleware inside the configure() of a startup.cs file. If we use any MVC based application, then we can use the exception handler middleware just as below. This code snippet demonstrates how we can configure the UseExceptionHandler middleware to redirect the user to an error page when any type of exception has occurred.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
{  
app.UseExceptionHandler("/Home/Error");  
app.UseMvc();  
}  


Now, we need to check this exception message. For that purpose, open the WeatherForecastController.cs file and add the below action method to throw an exception –
[Route("GetExceptionInfo")]  
[HttpGet]  
public IEnumerable<string> GetExceptionInfo()  
{  
string[] arrRetValues = null;  
if (arrRetValues.Length > 0)  
{ }  
return arrRetValues;  
}  


If we want to capture the details of the exception objects – i.e. like the stack trace, message, etc then we use the below code as the exception middleware –
app.UseExceptionHandler(  
    options =>  
    {  
        options.Run(  
            async context =>  
            {  
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;  
                context.Response.ContentType = "text/html";  
                var exceptionObject = context.Features.Get<IExceptionHandlerFeature>();  
                if (null != exceptionObject)  
                {  
                    var errorMessage = $"<b>Exception Error: {exceptionObject.Error.Message} </b> {exceptionObject.Error.StackTrace}";  
                    await context.Response.WriteAsync(errorMessage).ConfigureAwait(false);  
                }  
            });  
    }  
);  


For checking the output, just execute the API endpoint in any browser:

Define a Custom Exception Middleware to handle Exceptions in ASP.NET Core API
Also, we can write our custom middleware to handle any type of exceptions. In this section, we demonstrate how to create a typical custom middleware class. Custom middleware also provides much more flexibility to handle exceptions. We can add a stack trace, an exception type name, error code, or anything else which we want to include as a part of the error message. The below code snippet shows the typical custom middleware class:
    using Microsoft.AspNetCore.Http;    
    using Newtonsoft.Json;    
    using System;    
    using System.Collections.Generic;    
    using System.Linq;    
    using System.Net;    
    using System.Threading.Tasks;    
        
    namespace API.DemoSample.Exceptions    
    {    
        public class ExceptionHandlerMiddleware    
        {    
            private readonly RequestDelegate _next;    
        
            public ExceptionHandlerMiddleware(RequestDelegate next)    
            {    
                _next = next;    
            }    
        
            public async Task Invoke(HttpContext context)    
            {    
                try    
                {    
                    await _next.Invoke(context);    
                }    
                catch (Exception ex)    
                {    
                        
                }    
            }    
        }    
    }    


In the above class, a request delegate is passed to any middleware. The middleware either processes this or passes it to the next middleware in the chain. If the request is unsuccessful, then an exception will be thrown, and then the HandleExceptionMessageAsync method will be executed within the catch block. So, let's update the Invoke method code as shown below:
    public async Task Invoke(HttpContext context)  
            {  
                try  
                {  
                    await _next.Invoke(context);  
                }  
                catch (Exception ex)  
                {  
                    await HandleExceptionMessageAsync(context, ex).ConfigureAwait(false);  
                }  
            }  


Now, we need to implement the HandleExceptionMessageAsync method, as shown below:
    private static Task HandleExceptionMessageAsync(HttpContext context, Exception exception)  
            {  
                context.Response.ContentType = "application/json";  
                int statusCode = (int)HttpStatusCode.InternalServerError;  
                var result = JsonConvert.SerializeObject(new  
                {  
                    StatusCode = statusCode,  
                    ErrorMessage = exception.Message  
                });  
                context.Response.ContentType = "application/json";  
                context.Response.StatusCode = statusCode;  
                return context.Response.WriteAsync(result);  
            }  


Now, in the next step, we need to create a static class named ExceptionHandlerMiddlewareExtensions and add the below code within that class,
    using Microsoft.AspNetCore.Builder;  
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Threading.Tasks;  
      
    namespace API.DemoSample.Exceptions  
    {  
        public static class ExceptionHandlerMiddlewareExtensions  
        {  
            public static void UseExceptionHandlerMiddleware(this IApplicationBuilder app)  
            {  
                app.UseMiddleware<ExceptionHandlerMiddleware>();  
            }  
        }  
    }  


Now, in the last step, we need to turn on our custom middleware within the Configure method of the startup class, as shown below:
    app.UseExceptionHandlerMiddleware();  

Conclusion

Exception handling is a mainly cross-cutting concept for any type of application. In this article, we discuss the implementation process of the global exception handling concept. We can take the benefits of global exception handling in any ASP.NET Core application to ensure that every exception will be caught and return the proper details related to that exception. With the global exception handling, we just need to write the exception handling related code for our entire application just in one place. Any suggestions or feedback or query related to this article are most welcome.



ASP.NET Core 3.1.9 Hosting - HostForLIFE.eu :: Creating Text Editor Using ASP.Net and jQuery

clock November 10, 2020 07:51 by author Peter

This article explains how to create a Text Editor using ASP.NET and jQuery. First of all, add a new application to your Visual Studio and name it "ASPNet Text Editor".

Now in this application we will add two TextBoxes, one Button and a Hidden Field.
    <asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server" CssClass="textBox" onblur="Test()"></asp:TextBox>  
    <asp:Button ID="Button1" runat="server" Text="Show it Below" />  
    <asp:HiddenField ID="hdField" runat="server" />  
    <asp:TextBox ID="textBox2" TextMode="MultiLine" runat="server" CssClass="textBox2"></asp:TextBox>

As you can see, I provided the CSS Classes in the code above. That's because I had already created the CSS and then I passed its name to these controls.
You can check the CSS code by downloading the Zip Code provided at the start of the article.
 

After creating the CSS, provide their reference in the Head section of the page like this:
    <link href="CSS/demo.css" rel="stylesheet" type="text/css" />  
    <link href="CSS/demo2.css" rel="stylesheet" type="text/css" />


Now you need to add two jQuery files to your application named jquery-1.10.2.min.js and jquery-te-1.4.0.min.js. You will get these files from my application code provided in the Zip.
 
Provide this code after the Body tag:
    <script src="JS/jquery-1.10.2.min.js" type="text/javascript"></script>  
    <script src="JS/jquery-te-1.4.0.min.js" type="text/javascript"></script>  
    <script language="javascript" type="text/javascript">  
    $('.textEditor1').jqte();  
    $(".textBox2").jqte({  
         blur: function() {  
              document.getElementById('<%=hdField.ClientID %>').value = document.getElementById('<%=txtBox2.ClientID %>').value;  
         }  
    });  
    </script>


On the Button click pass this code:
    protected void btnText_Click(object sender, EventArgs e) {    
        textbox2.Text = hdFieldt.Value;    
    }   


Now your complete code will look like this:
    <head runat="server">  
        <title>ASP.NET Text Editor</title>  
        <link href="CSS/demo.css" rel="stylesheet" type="text/css" />  
        <link href="CSS/demo2.css" rel="stylesheet" type="text/css" />  
    </head>  
      
    <body>  
        <form id="Editor" runat="server">  
            <div>  
                <asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server" CssClass="textBox" onblur="Test()"></asp:TextBox>  
                <asp:Button ID="Button1" runat="server" Text="Show it Below" />  
                <asp:HiddenField ID="hdField" runat="server" />  
                <asp:TextBox ID="textBox2" TextMode="MultiLine" runat="server" CssClass="textBox2"></asp:TextBox>  
            </div>  
        </form>  
    </body>  
    <script src="JS/jquery-1.10.2.min.js" type="text/javascript"></script>  
    <script src="JS/jquery-te-1.4.0.min.js" type="text/javascript"></script>  
    <script language="javascript" type="text/javascript">  
    $('.textEditor1').jqte();  
    $(".textBox2").jqte({  
        blur: function() {  
            document.getElementById('<%=hdField.ClientID %>').value = document.getElementById('<%=txtBox2.ClientID %>').value;  
        }  
    });  
    </script>

Output



ASP.NET Core 3.1.9 Hosting - HostForLIFE.eu :: Health Monitoring In ASP.NET Core

clock November 4, 2020 09:13 by author Peter

The dream of every software engineer is to write a code in such a way that there won’t be any defects and none of the infrastructure will ever go down. But, that is not the case in the real world and with the Microservices architecture it has become even more difficult to identify the state of the container.

In fact, we need a mechanism in place to quickly identify and fix the issue at the earliest unless it turns out to be a bigger problem. This is where Health Monitoring comes into picture.

Health Monitoring in ASP.NET Core allows you to get near real-time state of the container. These monitoring mechanisms are handy when your application is dealing with components such as database, cache, url, message broker etc.

Implementing basic health monitoring
When developing ASP.NET Core Microservices, you can use a built-in health monitoring feature by using a nuget package Microsoft.Extension.Diagnostic.HealthCheck. These health monitoring features can be enabled by using a set of services and middleware.
public void ConfigureServices    
       (IServiceCollection services)    
{    
   services.AddControllers();    
   services.AddHealthChecks();    
}     
public void Configure(IApplicationBuilder app,    
IWebHostEnvironment env)    
{    
   if (env.IsDevelopment())    
   {    
      app.UseDeveloperExceptionPage();    
   }    
      app.UseHttpsRedirection();    
      app.UseRouting();    
      app.UseAuthorization();    
      app.UseEndpoints(endpoints =>    
      {    
        endpoints.MapControllers();    
        endpoints.MapHealthChecks("/api/health");    
      }    
}   


When you run the application, you will see the output as Healthy

Health Monitoring In ASP.NET Core
For two lines of code, not too bad. However, we can do much better.

Returning status in JSON format
By default, the output of the health monitoring is in “plain/text”. Therefore, we can see the health status as Healthy or UnHealthy. In order to see the detailed output with all the dependencies, the application has to be customized with “ResponseWriter” property which is available in AspNetCore.HealthChecks.UI.Client

Firstly, add the nuget package
dotnet add package AspNetCore.HealthChecks.UI    
dotnet add package AspNetCore.HealthChecks.UI.Client    


Now, let’s configure the application
endpoints.MapHealthChecks("/api/health",     
new HealthCheckOptions()    
 {    
    Predicate = _ => true,    
    ResponseWriter = UIResponseWriter.     
                WriteHealthCheckUIResponse    
 });   


Now, run the application and you will see the output in json format
{    
  "status": "Healthy",    
  "totalDuration": "00:00:00.0038176"    
}  


Health Status for URI’s

You can easily verify the status of the endpoints/uri’s by using nuget package

dotnet add package AspNetCore.HealthChecks.uris    

Now, let's modify our code to accommodate the uri’s
public void ConfigureServices    
     (IServiceCollection services)    
{    
     
   services.AddControllers();    
   services.AddHealthChecks()    
     .AddUrlGroup(new Uri    
            ("https://localhost:5001/weatherforecast"),    
             name: "base URL", failureStatus:     
             HealthStatus.Degraded)    
}   


You need to use AddUrlGroup method to verify the uri’s and in case of failure, the status of the url will be displayed as Degraded.

Now, run the application and the output will look similar.
{    
  "status": "Healthy",    
  "totalDuration": "00:00:00.1039166",    
  "entries": {    
    "base URL": {    
      "data": {},    
      "duration": "00:00:00.0904980",    
      "status": "Healthy",    
      "tags": []    
    }    
}   

Health Status for SQL Server
In order to verify the status of SQL Server database, I did database installation in docker; however, you can use local instance of database server.

You can install SQL Server in docker using below commands
//Docker pull command to install    
docker pull mcr.microsoft.com/mssql/server    
     
//Docker Run command     
docker run --privileged -e 'ACCEPT_EULA=Y'     
-e 'SA_PASSWORD=Winter2019' -p 1433:1433     
--name=MSSQL -d     
mcr.microsoft.com/mssql/server:latest    


Once the database is up and running, add the below nuget package.
dotnet add package AspNetCore.HealthChecks.SqlServer    
public void ConfigureServices    
 (IServiceCollection services)    
        {    
     
            services.AddControllers();    
            services.AddHealthChecks()    
                .AddUrlGroup(new Uri("https://localhost:5001/weatherforecast"), name: "base URL", failureStatus: HealthStatus.Degraded)              .AddSqlServer(Configuration.GetConnectionString("DefaultConnection"),    
                healthQuery: "select 1",    
                failureStatus: HealthStatus.Degraded,    
                name: "SQL Server");    
        }  


Note
In the HealthQuery, don’t use any fancy queries to verify the Database connection. The main purpose of using “Select 1” is that it takes less execution time.

Now run the application and your output will look similiar.
{    
  "status": "Healthy",    
  "totalDuration": "00:00:00.1039166",    
  "entries": {    
    "base URL": {    
      "data": {},    
      "duration": "00:00:00.0904980",    
      "status": "Healthy",    
      "tags": []    
    },    
    "SQL Server": {    
      "data": {},    
      "duration": "00:00:00.0517363",    
      "status": "Healthy",    
      "tags": []    
    }    
  }    
}   


Custom Health Check
Custom Health Check can be easily implemented by using IHealthCheck interface.
public class TodoHealthCheck : IHealthCheck    
    {    
        public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)    
        {    
            //Implement you logic here    
            var healthy = true;    
            if (healthy)    
                return Task.FromResult(HealthCheckResult.Healthy());    
            return Task.FromResult(HealthCheckResult.Unhealthy());    
        }    
    }    


The AddCheck method in Configure services is used to add health check with the specified name.
public void ConfigureServices(IServiceCollection services)    
       {    
           services.AddControllers();    
           services.AddHealthChecks()    
               .AddUrlGroup(new Uri("https://localhost:5001/weatherforecast"), name: "base URL", failureStatus: HealthStatus.Degraded)    
               .AddSqlServer(Configuration.GetConnectionString("DefaultConnection"),    
               healthQuery: "select 1",    
               failureStatus: HealthStatus.Degraded,    
               name: "SQL Server")    
               .AddCheck<TodoHealthCheck>("Todo Health Check",failureStatus:HealthStatus.Unhealthy);    
       }  


Now, run the application

{  
    "status": "Healthy",  
    "totalDuration": "00:00:00.0544065",  
    "entries": {  
        "base URL": {  
            "data": {},  
            "duration": "00:00:00.0527285",  
            "status": "Healthy",  
            "tags": []  
        },  
        "SQL Server": {  
            "data": {},  
            "duration": "00:00:00.0386450",  
            "status": "Healthy",  
            "tags": []  
        },  
        "Todo Health Check": {  
            "data": {},  
            "duration": "00:00:00.0001681",  
            "status": "Healthy",  
            "tags": []  
        }  
    }  
}  


Let’s visualize.

Display the output in the JSON format looks reasonable; however, visualizing the UI makes more sense and can be easily understandable for non-technical background people as well.

Add nuget package.

dotnet add package AspNetCore.HealthChecks.UI.InMemory.Storage    

To visualize the UI health check, you need to amend changes in services and middleware.
public void ConfigureServices(IServiceCollection services)    
        {    
     
            services.AddControllers();    
            services.AddHealthChecks()    
                .AddUrlGroup(new Uri("https://localhost:5001/weatherforecast"), name: "base URL", failureStatus: HealthStatus.Degraded)    
                .AddSqlServer(Configuration.GetConnectionString("DefaultConnection"),    
                healthQuery: "select 1",    
                failureStatus: HealthStatus.Degraded,    
                name: "SQL Server")    
                .AddCheck<TodoHealthCheck>("Todo Health Check",failureStatus:HealthStatus.Unhealthy);    
     
            services.AddHealthChecksUI(opt =>    
            {    
                opt.SetEvaluationTimeInSeconds(10); //time in seconds between check    
                opt.MaximumHistoryEntriesPerEndpoint(60); //maximum history of checks    
                opt.SetApiMaxActiveRequests(1); //api requests concurrency    
                opt.AddHealthCheckEndpoint("default api", "/api/health"); //map health check api    
            })    
            .AddInMemoryStorage();    
        }   

The Health Check UI endpoint comes by default as “/healthchecks-ui“. You can change this value by customizing it through the MapHealthCheckUI method.

In the code, I have set the polling interval as 10 seconds. It checks whether all the endpoints/databases etc within the application are working as expected.

Now run the application.

Health Monitoring In ASP.NET Core

Now, let’s stop the SQL Server from Docker container and verify the output
//Get Container ID    
docker ps    
     
//Stop Docker container for SQL Server    
docker stop <Container Id here>   


Health Monitoring In ASP.NET Core

Other Health checksFeatures.




ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: Experimenting With Service Lifetimes In .NET Core

clock October 20, 2020 08:37 by author Peter

In this article we'll have a look at different lifetime options we have registering service via built-in IoC container provided in .net core. As an example we'll use code provided in one of my previous articles.
 
To quiclky recap we have a Quartz.Net job which depends on a service.
    private readonly IDemoService _demoService;    
    public DemoJob(IDemoService demoService)    
    {    
        _demoService = demoService;    
    }   


Instead of injecting DemoService directly we provide IDemoService abstraction which DemoJob depends upon.
 
Understanding service lifetimes
 
In the abovementioned article, we have registered our services with scoped lifetime.
    var serviceCollection = new ServiceCollection();  
    serviceCollection.AddScoped<DemoJob>();  
    serviceCollection.AddScoped<IDemoService, DemoService>();  
    var serviceProvider = serviceCollection.BuildServiceProvider();  


However, there is no actual thinking presented here as to why we have chosen it over other options such as transient or singleton lifetime.
 
Let’s examine the other options. In order to achieve this, we’ll add some trace statements to our class constructors.
    public DemoService()  
    {  
        Console.WriteLine("DemoService started");  
    }  

And the job constructor:
    public DemoJob(IDemoService demoService, IOptions<DemoJobOptions> options)  
    {  
        _demoService = demoService;  
        _options = options.Value;  
        Console.WriteLine("Job started");  
    }  


The service registration is as follows,
    serviceCollection.AddTransient<DemoJob>();  
    serviceCollection.AddTransient<IDemoService, DemoService>();  


After we run the program we’ll observe the following output,
 
DemoService started
Job started
calling http://i.ua
DemoService started
Job started
calling http://i.ua
DemoService started
Job started
calling http://i.ua
 
The output is pretty self-explanatory: We create a new instance each time we call service. Changing both registrations to AddScoped or AddSingleton produces the same result,
 
DemoService started
Job started
calling http://i.ua
calling http://i.ua
calling http://i.ua
 
Both instances are constructed just once at application startup. Let’s consult with the documentation to see what are the difference between those lifetimes and why the produce the same result for a given example.
 
Scoped lifetime services are created once per client request (connection).
 
Here is what singleton does.
 
Singleton lifetime services are created the first time they’re requested.
 
So in our case, we have a single request because we use console application. This is the reason why both service lifetimes act the same.
 
The last topic most of DI-related articles do not cover is a composition of services with different lifetimes. Although there is something worth mentioning. Here is the example of registration.
    serviceCollection.AddSingleton<DemoJob>();  
    serviceCollection.AddTransient<IDemoService, DemoService>();  


This  means that we inject transient dependency into singleton service. One might expect that since we declared IDemoService as transient it will be constructed each time.
 
The output, however, is quite different,
 
DemoService started
Job started
calling http://i.ua
calling http://i.ua
calling http://i.ua
 
So again both services are constructed at the application startup. Here we see that lifetime of transient service gets promoted by the service that uses it. This leads to an important application. The service we’ve registered as transient might be not be designed to be used as a singleton because it is not written in thread-safe fashion or for some other reasons. However, it becomes singleton in this case which may lead to some subtle bugs. This brings us to the conclusion that we shouldn’t register services as singletons unless we have some good reason for it; i.e., service that manages global state. It’s preferable to register services as transient.
 
The opposite, however, yields no surprises.

    serviceCollection.AddTransient<DemoJob>();  
    serviceCollection.AddSingleton<IDemoService, DemoService>();  

produces
 
DemoService started
Job started
calling http://i.ua
Job started
calling http://i.ua
Job started
calling http://i.ua
 
Here each new instance of a job reuses the same singleton DemoService.

 



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: Dynamic Service Registration In ASP.NET Core Dependency Injection Container

clock October 16, 2020 09:45 by author Peter

In ASP.NET Core, whenever we inject a service as a dependency, we must register this service to ASP.NET Core Dependency Injection container. However, registering services one by one is not only tedious and time-consuming, but it is also error-prone. So here, we will discuss how we can register all the services at once dynamically. To register all of the services dynamically, we will use TanvirArjel.Extensions.Microsoft.DependencyInjection library. This is a small but extremely useful library that enables you to register all your services into ASP.NET Core Dependency Injection container at once without exposing the service implementation.

First, install the latest version of TanvirArjel.Extensions.Microsoft.DependencyInjection NuGet package into your project as follows,
    Install-Package TanvirArjel.Extensions.Microsoft.DependencyInjection  

Using Marker Interface
Now let your services inherit any of the ITransientService, IScoperService, and ISingletonService marker interfaces as follows,
    using TanvirArjel.Extensions.Microsoft.DependencyInjection

    // Inherit `IScopedService` interface if you want to register `IEmployeeService` as scoped service.    
    public class IEmployeeService : IScopedService     
    {    
        Task CreateEmployeeAsync(Employee employee);    
    }    
        
    internal class EmployeeService : IEmployeeService    
    {    
       public async Task CreateEmployeeAsync(Employee employee)    
       {    
           // Implementation here    
       };    
    }    

ITransientService, IScoperService, and ISingletonService are available in TanvirArjel.Extensions.Microsoft.DependencyInjection namespace.
 
Using Attribute
Now mark your services with any of the ScopedServiceAttribute, TransientServiceAttribute, and SingletonServiceAttribute attributes as follows,
    using TanvirArjel.Extensions.Microsoft.DependencyInjection

    // Mark with ScopedServiceAttribute if you want to register `IEmployeeService` as scoped service.  
    [ScopedService]  
    public class IEmployeeService  
    {  
            Task CreateEmployeeAsync(Employee employee);  
    }  
          
    internal class EmployeeService : IEmployeeService   
    {  
        public async Task CreateEmployeeAsync(Employee employee)  
        {  
           // Implementation here  
        };  
    }  


ScopedServiceAttribute, TransientServiceAttribute, and SingletonServiceAttribute are available in TanvirArjel.Extensions.Microsoft.DependencyInjection namespace.
 
Now in your ConfigureServices method of the Startup class,
    public void ConfigureServices(IServiceCollection services)    
    {    
       services.AddServicesOfType<IScopedService>();   
       services.AddServicesWithAttributeOfType<ScopedServiceAttribute>();    
    }    


AddServicesOfType<T> is available in TanvirArjel.Extensions.Microsoft.DependencyInjection namespace.
 
Moreover, if you want only specific assemblies to be scanned during type scanning,
    public static void ConfigureServices(IServiceCollection services)  
    {  
        // Assemblies start with "TanvirArjel.Web", "TanvirArjel.Application" will only be scanned.  
        string[] assembliesToBeScanned = new string[] { "TanvirArjel.Web", "TanvirArjel.Application" };  
        services.AddServicesOfType<IScopedService>(assembliesToBeScanned);  
        services.AddServicesWithAttributeOfType<ScopedServiceAttribute>(assembliesToBeScanned);  
    }  


That's it! The job is done! It is as simple as above to dynamically register all your services into ASP.NET Core Dependency Injection container at once. If you have any issues, you can submit it to the Github Repository of this library. You will be helped as soon as possible.



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: Validating Data Model Using Fluent Validation in ASP.NET Core WebApi

clock October 8, 2020 08:45 by author Peter

Validating user input is a basic function in a web application. For production systems, developers usually spend a lot of time writing a lot of code to complete this function. If we use Fluent Validation to build the ASP.NET Core Web API, the task of input validation will be much easier than before. Fluent Validation is a very popular. NET library for building strong type validation rules.

Configuration project
Step 1: Download fluent validation

We can use nuget to download the latestFluentValidationlibrary
PM> Install-Package FluentValidation.AspNetCore

Step 2: Add the Fluent Validation service
We need to be in the ____________Startup.csAdd Fluent Validation Service to File
public void ConfigureServices(IServiceCollection services)
{
  // mvc + validating
  services.AddMvc()
  .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
  .AddFluentValidation();
}


Adding Checker
FluentValidationA variety of built-in calibrators are provided. In the following examples, we can see two of them.
    NotNull Checker
    NotEmpty Checker

Step 1: Add a data model that needs to be validated

Now let’s add oneUserClass.
public class User
{
  public string Gender { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string SIN { get; set; }
}


Step 2: add verifier class
UseFluentValidationTo create a validator class, the validator class needs to inherit from an abstract classAbstractValidator
public class UserValidator : AbstractValidator<User>
{
  public UserValidator()
  {
   //Add rules here
  }
}


Step 3: Add validation rules
In this example, we need to verify that FirstName, LastName, SIN can’t be null, can’t be empty. We also need to verify that the SIN (Social Insurance Number) number is legitimate.
public static class Utilities
{
  public static bool IsValidSIN(int sin)
  {
   if (sin < 0 || sin > 999999998) return false;

   int checksum = 0;
   for (int i = 4; i != 0; i--)
   {
     checksum += sin % 10;
     sin /= 10;

     int addend = 2 * (sin % 10);
     
     if (addend >= 10) addend -= 9;
     
     checksum += addend;
     sin /= 10;
   }
     
   return (checksum + sin) % 10 == 0;
  }
}


Here we areUserValidatorClass, add validation rules
public class UserValidator : AbstractValidator<User>
{
  public UserValidator()
  {
   RuleFor(x => x.FirstName)
   .NotEmpty()
   .WithMessage("FirstName is mandatory.");

   RuleFor(x => x.LastName)
   .NotEmpty()
   .WithMessage("LastName is mandatory.");

   RuleFor(x => x.SIN)
   .NotEmpty()
   .WithMessage("SIN is mandatory.")
   .Must((o, list, context) =>
   {
     if (null != o.SIN)
     {
      context.MessageFormatter.AppendArgument("SIN", o.SIN);
      return Utilities.IsValidSIN(int.Parse(o.SIN));
     }
     return true;
   })
   .WithMessage("SIN ({SIN}) is not valid.");
  }
}


Step 4: Injecting authentication services
public void ConfigureServices(IServiceCollection services)
{
  // Add validator
  services.AddSingleton<IValidator<User>, UserValidator>();
  // mvc + validating
  services
    .AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddFluentValidation();
}


Step 5:Startup.csManage your validation errors
In ASP.NET Core 2.1 and above, you can override the default behavior (ApiBehavior Options) managed by ModelState.
public void ConfigureServices(IServiceCollection services)
{
  // Validators
  services.AddSingleton<IValidator<User>, UserValidator>();
  // mvc + validating
  services
    .AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddFluentValidation();

  // override modelstate
  services.Configure<ApiBehaviorOptions>(options =>
  {
    options.InvalidModelStateResponseFactory = (context) =>
    {
     var errors = context.ModelState
       .Values
       .SelectMany(x => x.Errors
             .Select(p => p.ErrorMessage))
       .ToList();
      
     var result = new
     {
       Code = "00009",
       Message = "Validation errors",
       Errors = errors
     };
      
     return new BadRequestObjectResult(result);
    };
  });
}

When data model validation fails, the program executes this code.

In this example, I set up how to display errors to the client. In the returned result here, I just include an error code, error message and error object list.

Let’s take a look at the final results.

Using Verifier
Verifier is very easy to use here.

You just need to create an action and put the data model that needs to be validated into the action parameters.

Since the authentication service has been added to the configuration, when this action is requested,FluentValidationYour data model will be validated automatically!

Step 1: Create an action using the data model to be validated
[Route("api/[controller]")]
[ApiController]
public class DemoValidationController : ControllerBase
{
  [HttpPost]
  public IActionResult Post(User user)
  {
   return NoContent();
  }
}



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in