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 3.1 Hosting :: Is .NET Core 3.1 Secure?

clock November 5, 2020 09:12 by author Scott

Well, Microsoft will release Asp.net 5 version, now it is on RC version and of course we will support this feature on our hosting environment. Asp.net Core keep improving and it is very fast. Previously, we have also advise steps by steps to migrate your Asp.net Core to latest Asp.net Core 3.1. Why? It because with latest Asp.net Core, it will be more secure and improving your website speed.

Why .NET Core is Better for Security

If you’ve ever tried to update an old house, you know that it can be challenging. As we’ve learned more about home construction and materials we have updated building codes and standards to ensure that modern homes have far few troubles and are far more efficient. .NET Core is the same thing.

Microsoft built .NET Core from the ground up with twenty years of lessons learned and updated best practices built in. Application and website security are not add-ons and patches. Security was a fundamental attribute of design and structure which means we can build more secure apps with less complexity and faster performance. And this is especially important in the age of platforms and the cloud when APIs and service calls are flying back and forth to keep your business tech connected to the world at the speed of light.

Importantly, one of the lessons Microsoft learned was to always be looking forward. So even though .NET Core was built to be cloud-native, they were also looking at the fledgling technologies of connected devices (IoT) and edge-computing. So, this forward-looking technology is wired in as well.

In other words, many of the same things that make .NET Core orders of magnitude faster than previous .NET iterations also make it more secure.

Security for .NET Core 3.1

Security is still in the hands of the developers and admins who write, deploy, and maintain the applications. The best practices that have been developed over the last two decades – some of which we’ve documented over the years — are still best practices. .NET Core 3.1 just makes them easier to deploy, easier to maintain, and faster to run.

The basics still apply, including:

Manage Your Identity Providers in .NET 3.1

Great security starts with keeping the black-hats out and letting the good guys in to do business. Before we talk about things like authentication, we need to start with the tools to do that user authentication. .NET Core 3.1 natively includes Identity providers. But it also supports major third-party identity services, including from the major social networks (e.g., Facebook, Twitter, LinkedIn).

Authentication First / Authorization Second

Old-school applications used to focus on Authorization — which allowed users to access certain functions or features based upon roles first. But once given any degree of access, a system is less secure if that individual has bad intent.

Enforce HTTPS

Deploying HTTPS is not the same as enforcing it.

Encryption keys used to cost money. But we live in a time when adding encryption to your web application is either free or VERY inexpensive. Three years ago we wrote extensively about great services like
LetsEncrypt that offer free basic encryption. But there are a surprising number of sites that still have no encryption at all and many that do offer it as a security to visitors but do not enforce it as a security for and across the application itself.

Common Vulnerability Issues

According to Microsoft, the most common vulnerability types to guard against in .NET Core 3.1 are as follows:

  • Cross-Site Scripting (XSS) — An attacker places client-side scripts inside vulnerable website code, allowing the interception of cookies or access tokens.
  • SQL Injection — An attacker places executable database statements in an entry field. This is one of the most common attack types today. You can read about SQL injections on our blog.
  • Cross-Site Request Forgery (XSRF) — An attacker takes advantage of a previously authorized session. To learn more about
  • Open Redirect — Page/URL redirects are important tools in the hands of coders. But vulnerable websites can have redirects tampered with to point to a malicious URL. Information on preventing this kind of attack can be found on Microsoft’s website.

Summary - .NET Core 3.1 is Fully Secure

It is our opinion that the latest version of .NET Core 3.1.x is the safest and most secure development platform available today for creating business-class and enterprise-class websites and applications. But as with all development frameworks, deploying best practices and proper maintenance are key.



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();
  }
}



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: Web Protection Library (WPL)

clock September 15, 2020 09:15 by author Peter

Web applications have always been threatened by a series of attacks. Thankfully, IT Security organizations have worked tirelessly to secure web application development by coming up with ways to mitigate malicious attacks. One of these developments is the Microsoft Web Protection Library, a tool that can be used to protect ASP.NET web application and Windows applications malicious attacks

In this article, we are going to learn about Microsoft Web Protection Library. We will first look at threats surrounding web applications and then delve into the protection measures that WPL introduces.
 
What is the Microsoft Web Protection Library (WPL)?
The WPL is a set of .NET assemblies put together for protection against the most common attack vectors. WPL comprises the Anti-XSS which is a bunch of encoding functions for user input which includes JavaScript, XML, CSS, HTML, and HTML attributes. WPL also has a Security Runtime Engine which works as a shield protecting web applications from the common attack vectors.
 
The Anti-XSS Library
A cross-site script (XSS) attack is a very common attack that involves malicious user input (e.g. in the form of scripts) from attackers using poorly validated form fields on web applications. Anti-XSS provides a class that can be used to encode all user input on forms in MVC, web pages, and web forms applications. It uses a white-list approach which entails that it checks the expected input from users and if not recognized it classifies that input as a possible danger or possible harm. It comprises of encoders for:
    HTML
    HTML Attributes
    CSS
    XML
    JavaScript

Anti-XSS Examples
ASPX
<td><asp:Label id='lblIDNO' runat='server'></asp:Label></td>
 
ASPX.CS
lblIDNO.Text = Request['IDNO'];
 
Normally an unsafe way of rendering can be done as in the above codes snippet but Anti-XSS provides a safe way using the HTML encoding.
 
ASPX
<td><asp:Label id='lblIDNO' runat='server'></asp:Label></td>
 
ASPX.CS
lblIDNO.Text = Microsoft.Security.Application.Encoder.HtmlEncode(Request['IDNO']);
 
In the above code, the dynamic IDNumber property is being encoded using the Anti-XSS HTML encoder before it is put in the HTML context. The same could be done using a shortcut ()
 
The code below shows an example of JavaScript encoding:
<a onclick='<%# string.Format('isDelete({0})', Microsoft.Security.Application.Encoder.JavaScriptEncode(Item.Address)) %>'>Delete</a>
 
Scripts should also be encoded just in case an attacker uses a malicious script that might end up executing unwanted commands at the server-side.
 
Dynamic data including URLs should be encoded before they are written in href because they may contain malicious input or untrusted URL and end up exfiltrating data to attacker sites.
 
The following code shows an example of URL encoding using WPL:
<a href=<%# Microsoft.Security.Application.Encoder.UrlEncode(Item.Url) %>>Customer Details</a>
 
It very important that developers understand the various malicious vectors used by attackers which can be implemented using threat modeling at design time. Safety can be applied to applications at development time or to existing applications and developers need to review code which gives users output, determine if the given output has any untrusted input parameters, also understand the context in which untrusted input is being compromised to give output and lastly encode the output properly. WPL uses the whitelist approach and when it is not sure that the input is trusted or not, it assumes that it is not and rejects the input as untrusted. Most potential dangers are found in form fields, query strings, and cookie contents.
 
In order to use Anti-XSS encoders after installation of WPL, you need to make use of the following directive:
using Microsoft.Security.Application;
 
WPL Architecture
The following is a diagram that shows the architectural pattern of the WPL.

The impact that can be caused by malicious attacks on businesses and individuals is so great that it is very important that developers and analysts try to find all possible vulnerabilities and not overlook certain aspects of the application. WPL is an effective tool for protecting individuals as well as organizations from such devastating web attacks.

 



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: Merge Different File Formatted Documents Into A Single PDF

clock September 7, 2020 08:55 by author Peter

Why merge different documents?
There are a lot of common yet crucial reasons to merge documents. Let's understand the need with some use-cases.
 
Real estate
When you buy or lease a property, you have to go through a lot of documentation (e.g. mortgage, loan application, agreements, various expense recordings). Such documentation is mostly recorded in multiple file formats (e.g. PDF, Word, Excel, Presentation). Wouldn't it be super if you could compile all the documents into a single understandable format such as PDF?
 
Archived documents
Most of the time we have a lot of electronic documents saved in various formats. They all have similar content and need to be combined. For example Excel file with charts, or Word file swith some formatted text. These details could be combined in a single PDF. Eventually, you can share this resultant PDF with colleagues or print it without any issue.
 
Merge documents to PDF
 
Let's see how we merge DOC, PPT, XLS and PDF files into a single PDF.
    using (Merger merger = new Merger(@"c:\document1.pdf"))  
    {  
        merger.Join(@"c:\document2.doc");  
        merger.Join(@"c:\document3.ppt");  
        merger.Join(@"c:\document4.xls");  
        merger.Save(@"c:\merged.pdf");  
    }  


Download the DLL and add it as a reference in your .NET project (existing or new).

 



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: How To Call Web API In Another Project From C#?

clock August 26, 2020 09:28 by author Peter

This article explains how to call a web API from another project using C# instead of making an Ajax call. I'm  creating a web API in MVC  in project1 and want to call this API in another project (like.MVC,Asp.net,.core etc) project but don't want to make any Ajax requests.
So let's see how to make a C# request for an Api Call.

Here I  am creating an API in MVC for getting  a statelist   in Project 1.
 public class StateController : ApiController 
   { 
[HttpGet] 
       [Route("api/State/StateList")] 
       public List<StateDto> StateList() 
       { 
           List<StateDto> StateList = new List<StateDto>(); 
           SqlConnection sqlConnection = new SqlConnection(); 
 
           string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString; 
           SqlCommand sqlCommand = new SqlCommand(); 
           sqlConnection.ConnectionString = connectionString; 
           sqlCommand.CommandType = CommandType.Text; 
           sqlCommand.CommandText = "Select * From lststate where deletedbyid is null"; 
           sqlCommand.Connection = sqlConnection; 
           sqlConnection.Open(); 
           DataTable dataTable = new DataTable(); 
           dataTable.Load(sqlCommand.ExecuteReader()); 
           sqlConnection.Close(); 
 
           if (dataTable != null) 
           { 
               foreach (DataRow row in dataTable.Rows) 
               { 
                   StateList.Add(new StateDto 
                   { 
                       Id = (int)row["id"], 
                       StateCode = row["Statecode"].ToString(), 
                       StateName = row["StateName"].ToString(), 
                       CompanyId = (int)row["Companyid"], 
                       CreatedDate = (DateTime)row["CreatedDate"] 
                   }); 
 
               } 
               return StateList; 
           } 
           else 
           { 
 
           } 
 
 
       } 


Project 2 where we want to call this API.
public List<StateDto> StateIndex() 
  { 
      var responseString = ApiCall.GetApi("http://localhost:58087/api/State/StateList"); 
      var rootobject = new JavaScriptSerializer().Deserialize<List<StateDto>>(responseString); 
      return rootobject; 
  } 


ApiCall.cs class 
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Net; 
using System.Text; 
using System.Threading.Tasks; 
 
namespace MaheApi.Dto 

    public static class ApiCall 
    { 
        public static string GetApi(string ApiUrl) 
        { 
 
            var responseString = ""; 
            var request = (HttpWebRequest)WebRequest.Create(ApiUrl); 
            request.Method = "GET"; 
            request.ContentType = "application/json"; 
 
            using (var response1 = request.GetResponse()) 
            { 
                using (var reader = new StreamReader(response1.GetResponseStream())) 
                { 
                    responseString = reader.ReadToEnd(); 
                } 
            } 
            return responseString; 
 
        } 
 
        public static string PostApi(string ApiUrl, string postData = "") 
        { 
 
            var request = (HttpWebRequest)WebRequest.Create(ApiUrl); 
            var data = Encoding.ASCII.GetBytes(postData); 
            request.Method = "POST"; 
            request.ContentType = "application/x-www-form-urlencoded"; 
            request.ContentLength = data.Length; 
            using (var stream = request.GetRequestStream()) 
            { 
                stream.Write(data, 0, data.Length); 
            } 
            var response = (HttpWebResponse)request.GetResponse(); 
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 
            return responseString; 
        } 
  } 
}
 

Here we get data in StateIndex method



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: How To Write In Hindi (Or Another Font) In ASP.NET Core?

clock August 18, 2020 13:27 by author Peter

In this blog I am explaining how to read and write in the Hindi Language (or we can use any language as per our requirement).
 
Here I will explain how to write Hindi in an ASP.NET Core text box using Devlys_010 font. So please follow the below steps .
 
Step 1
Download Devlys_010 font in any format like .ttf , .woff, etc. You can download from here
This is a zip file so you can extract it in the folder.
 
Step 2
Open your Asp.Net core project and create a new folder under css. Give the folder a name like Fonts.
 
Under the Fonts folder paste the downloaded font which we have already exctracted. And now create one css file and give it the name font.css

Here you can see I have added a screenshot. I have pasted a ttf format font and created a font.css under a newly-created folder, Fonts.
 
Step 3
Now open font.css in your editor. Now we add font in our project using @font-face.
 
So write the css code in your font.css like below:
    @font-face { 
        font-family: 'Devlys_010'; 
        src: local('Devlys_010'),url('./Devlys_010.ttf') format('truetype'); 
    } 

Step 4

Now create a new class css in font.css below @font-face and add a font family which we have using @font-face.
    .hFont { 
        font-family: 'Devlys_010' !important; 
    } 

Now you can see all css code in font.css
    @font-face { 
        font-family: 'Devlys_010'; 
        src: local('Devlys_010'),url('./Devlys_010.ttf') format('truetype'); 
    } 
     
    .hFont { 
        font-family: 'Devlys_010' !important; 
    }
 

Here I have added .hFont class -- you can change this name.
 
Step 5
Now go to your cshtml page where you want to write your Hindi font. This means If you have used input type text then just add class hFont like below.
 
And add css in header for getting our css code.
    <link href="~/css/fonts/font.css" rel="stylesheet" /> 

Now add css class for writing Hindi font. See in the below code I have added hFont class in input type.
    <input asp-for="@Model.AdminMaster.AdminName" class="form-control hFont" id="txtAdminName" /> 

    OR
    <input type = "text" class="form-control hFont" id="txtAdminName" /> 

Note

You can use any other font also just add font in css and use it. Also use any language font like Gujarati, Marathi, Urdu or any other language.  

 



ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: HTTP Requests Using IHttpClientFactory

clock August 11, 2020 13:14 by author Peter

The very first time Microsoft launched the HttpClient in .NET Framework 4.5, it became the most popular way to consume a Web API HTTP request, such as Get, Put, Post, and Delete in your .NET server-side code. However, it has some serious issues, for example, disposing of the object like HttpClient object doesn’t dispose of the socket as soon as it is closed. There are also too many instances open so that it affecting the performance and private HttpClientor shared HttpClient instance not respecting the DNS Time.

When Microsoft released dotnet core 2.1, it introduced HttpClientFactory that solves all these problems.

Basically, it provides a single place (central place) for configuration and consumption HTTP Verbs Client in your application IHttpClientFactory offers the following benefits,

  Naming and configuring HttpClient instances.
  Build an outgoing request middleware to manage cross-cutting concerns around HTTP requests.
  Integrates with Polly for transient fault handling.
  Avoid common DNS problems by managing HttpClient lifetimes.

There are the following ways to use IHttpClientFactory.
  Direct HttpClientFactory
  Named Clients
  Typed Clients

We will see an example one by one for all 3 types...

Direct HttpClientFactory

In dotnet core, we have Startup.cs class, and inside this class, we have the ConfigureService method. In this method we use middleware, where we inject some inbuilt/custom pipeline.

So for HttpClientFactory we need to register HttpClient like below:
services.AddHttpClient(); 

Now the question is how to use this in our API controller.

So here is the example of Direct HttpClientFactory use in controller:
  public class HttpClientFactoryController: Controller { 
      private readonly IHttpClientFactory _httpClientFactory; 
      public HttpClientFactoryController(IHttpClientFactory httpClientFactory) { 
              _httpClientFactory = httpClientFactory; 
          } 
          [HttpGet] 
      public async Task < ActionResult > Get() { 
          var client = _httpClientFactory.CreateClient(); 
          client.BaseAddress = new Uri("http://api.google.com"); 
          string result = await client.GetStringAsync("/"); 
          return Ok(result); 
      } 
  }


Here in this example we have pass IHttpClientFactory is a dependency injection and directly use _httpClientFactory.CreateClient();

This example is better in this situation when we need to make a quick request from a single place in the code

Named Clients
Just above I have explained how to register the middleware in startup.cs class in configureService method for HttpClient same we can use for Named Clients as well, but this is useful when we need to make multiple requests from multiple locations.

We can also do some more configuration while registering, like this:
  services.AddHttpClient("g", c => 
  { 
     c.BaseAddress = new Uri("https://api.google.com/"); 
     c.DefaultRequestHeaders.Add("Accept", "application/json"); 
  }); 


Here in this configuration, we use two parameter names and an Action delegate taking a HttpClient

We can use the named client in the API controller in this way:
  public class NamedClientsController: Controller { 
      private readonly IHttpClientFactory _httpClientFactory; 
      public NamedClientsController(IHttpClientFactory httpClientFactory) { 
              _httpClientFactory = httpClientFactory; 
          } 
          [HttpGet] 
      public async Task < ActionResult > Get() { 
          var client = _httpClientFactory.CreateClient("g"); 
          string result = await client.GetStringAsync("/"); 
          return Ok(result); 
      } 
  }


Note
"g" indicates names client that I use in during registration and also call from the API action method

Typed Clients

A types client provides the same capabilities as named clients but without the need to use strings as keys in configuration. Due to this it also provide IntelliSense and compiler help when consuming clients. It provides a single location to configure and interact with a particular httpclient

It works with dependency injection and can be injected where required in the application.

A typed client accepts an HttpClient parameter in its constructor,

We can see here by an example that I have defined custom class for httpclient:
  public class TypedCustomClient { 
      public HttpClient Client { 
          get; 
          set; 
      } 
      public TypedCustomClient(HttpClient httpClient) { 
          httpClient.BaseAddress = new Uri("https://api.google.com/"); 
          httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); 
          httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample"); 
          Client = httpClient; 
      } 
  }

Now we can register this as a typed client using in this way in startup.cs clss under configureService method.

  services.AddHttpClient<TypedCustomClient>(); 

Now this time we see how we can use it in API controller,
  public class TypedClientController: Controller { 
      private readonly TypedCustomClient _typedCustomClient; 
      public TypedClientController(TypedCustomClient typedCustomClient) { 
              _typedCustomClient = typedCustomClient; 
          } 
          [HttpGet] 
      public async Task < ActionResult > Get() { 
          string result = await _typedCustomClient.client.GetStringAsync("/"); 
          return Ok(result); 
      } 
  }


Now we have learned all three types to use.

But here is one better way to use typeclient using an interface.

We will create an interface and encapsulate all the logic here, that also helps in writing UTC as well

Here is an example:
  public interface ICustomClient 
  { 
    Task<string> GetData(); 
  } 


Now inherit this interface in custom class
  public class TypedCustomClient: ICustomClient { 
      public HttpClient Client { 
          get; 
          set; 
      } 
      public TypedCustomClient(HttpClient httpClient) { 
          httpClient.BaseAddress = new Uri("https://api.google.com/"); 
          httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); 
          httpClient.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample"); 
          Client = httpClient; 
      } 
  }


Register this in startup class:
  services.AddHttpClient<ICustomClient, TypedCustomClient>(); 

  public class CustomController: Controller { 
      private readonly ICustomClient _iCustomClient; 
      public ValuesController(ICustomClient iCustomClient) { 
              _iCustomClient = iCustomClient; 
          } 
          [HttpGet] 
      public async Task < ActionResult > Get() { 
          string result = await iCustomClient.GetData(); 
          return Ok(result); 
      } 
  }


Here we are using the interface for the same, so it would be good to go for repository mock.

HostForLIFE.eu ASP.NET Core 3.1.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



 



About HostForLIFE.eu

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 offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in