fabiochiu/medium-articles huggingface dataset:
Custom Validation Attribute Asp.net Core 2019
By: Sagar Jaybhay
Tags: Web Development, Csharp, Sagar Jaybhay, Aspnetcore, Aspnet

How to Create Custom Validation Attrbute Asp.Net Core?

Built-in Validation Attribute

Required Range StringLength RegularExpression Compare Etc..

When in your project we have some requirements that can not be full fill with some in-built validation attributes then we need to create some Custom validation attribute. In this, we have created one CustomValidator class which inherits from ValidationAttribute inbuilt class. After inheriting from this we need to override the IsValid method.

Nowin our example, we have to achieve the functionality of we are valid for only Gmaildomain mail-id. Other than Gmail we restrict the user for creating an account.

After creating this CustomValidator attribute you can use this as our normal attributes.

Custom Validation Attribute Class in Asp.net core

Now we are adding code for this validation

public class CustomValidator:ValidationAttribute

{

private string allowedDomain { get; set; }

public CustomValidator(string allowedDomain)

{

this.allowedDomain = allowedDomain;

}

public override bool IsValid(object value)

{

string[] array = value.ToString().Split("@");

if (array.Length > 1)

return array[1].ToLower() == allowedDomain.ToLower();

else

{

return false;

}

}

}

In this code, we have created one property allowed domain which isfor we pass the domain name from our CustomValidator as a parameter.

See below code

public class RegistrationVIewModel

{



[Required]

[EmailAddress]

[Remote(controller:"Account",action: "IsUsedEmailID")]

[CustomValidator(allowedDomain:"gmail.com",

ErrorMessage = "Email Domain Must Be gmail.com")]

public string Email { get; set; }



[Required]

[DataType(DataType.Password)]

public string Password { get; set; }





[Required]

[DataType(DataType.Password)]

[Display(Name = "Confirm Password")]

[Compare("Password",ErrorMessage = "Password and Confirm Password not match.")]

public string ConfirmPassword { get; set; }

}

Now see the image

Custom Validation Attribute Declaration in asp.net core

Here we pass that parameter for that reason we need to createproperty and constructor in this class and need to catch this.

In this we have split the email id with the use of @ symbol thenwe check first array length greater than 1 and then we check with email iddomain name.

See the below output

Here we pass that parameter for that reason we need to createproperty and constructor in this class and need to catch this.

In this we have split the email id with the use of @ symbol thenwe check first array length greater than 1 and then we check with email iddomain name.

See the below output

GitHub Project Link: https://github.com/Sagar-Jaybhay/LearnAspNetCore
API to JSON Serialization C# — A Wonderful journey to the rabbit hole 💊
By: Pritom Purkayasta
Tags: C Sharp Programming, Dot Net Framework, Dotnet, Json, Aspnetcore

Json stands for Javascript Object Notation, which is a format that encodes objects in a string. In JSON there is two most important part. One is Serialization and another one is you guessed it Deserialization.

What does Serialization or Deserialization even means?

In the most easiest word I can describe is, serialization means to convert an object to a string and deserialization is the convert string to an object (the opposite one).

In a nutshell, Serialization is the process of converting an object into a stream of bytes to store an object or save it into memory or a database, or even a file. If you want to know more about serialization you can see this.

So for this demo, I have created an empty Console c# application and installed Newtonsoft.Json package from NuGet Package Manager.

In this app, we are going to get data from a public API. I like programming jokes so I scrap from this 😜😆 (You can visit here to customize your public jokes API for fun though)

So to consume api from your app there are lots of packages. Each package comes with its pros and cons. We are going to explore HttpClient as it is the new kid in the town.

We are using HttpClient so we are using GetAsync(url) function to get the results from the API. As it is the async method we are using .Result to get the result from the API. So response from API is an instance of HttpResponseMessage, it has a status code and this library comes with quite a handful of methods to get things done more easily. Then at last we are converting this into a string (although we can convert it into many types such as byte array, stream etc).

So to typecast it into a class we are going to need a class. Let's create this class depending on the property that I will be getting from that API and named it JokesApi.

Now the deserialization techniques come in the play. In c# Json.net comes handy when handling such things.

We are casting the string as the class type that we newly created. As we are getting one response only so we are casting as it is. If we want the list we would use IList<classtype> to cast it.

That's the console output.

You will find everything on GitHub. 🌙🏴‍☠️😎
Volosoft Announces the .NET Foundation Sponsorship
By: Zülal Dülek
Tags: Volosoft, Web Development, Netfoundation, Aspnetcore, Web App Development

We are proud of being a corporate sponsor of the .NET Foundation today!

At Volosoft, we always think of open-source first. Volosoft has been established based on an open-source project, ASP.NET Boilerplate. We are still spending most of our time developing open-source projects and building communities, focusing on the ABP.IO platform these days.

As a company that succeeds in building a business model around an open-source platform, we are aware that it is hard to create and maintain a serious open-source project. We appreciate everyone who contributes to the open-source software ecosystem.

The .NET Foundation is an independent, non-profit organization established to support an innovative, commercially friendly, open-source ecosystem around the .NET platform.

We have been closely following the .NET Foundation since its first days. There are many successful projects under the umbrella of the .NET Foundation, and we are also using many open-source projects in our products.

We are looking forward to working closely with all open-source developers and supporting the .NET Foundation.

Halil İbrahim Kalkan

Co-Founder, Volosoft
Building Cloud Aware Web Api is Easier than You Think
By: Ashraful Alam
Tags: Aspnet Development, Webapi, Entity Framework Core, Net Core, Aspnetcore

Building cloud aware web api is easier than you think.

Check this cool open source project here: https://eisk.github.io/eisk.webapi.

Built with .net core, it comes with frameworks, tools, code samples and easy to read documentation.

Getting Started with EISK Web Api

EISK makes it easy to write scalable and secured web api on top of Microsoft’s new cutting edge .net core technologies.

With an optional set of customizable utility classes, samples and tools, it lets you creating new web api straight away without wide technical experience or learning curve.

Sample Use Case

Using a simple table entity ‘Employee’ it demonstrates all aspect of web development including layered architecture following DDD, micro service, unit and integration tests, building and deploying in cloud environment.

Here is a simple CRUD use case illustrated in the default template:

Creating a new employee record

Read existing employee records

Update an existing employee record

Delete existing employee records

Core Technology Areas

ASP.NET Core 2.0 (Web Api)

Entity Framework Core 2.0

C# 7.0

Visual Studio 2017

Azure App Services

System Requirements (Development)

Visual Studio 2017 (Free Community Edition or higher)

QuickStart Guide

Getting started with EISK Web Api is pretty easy.

You can either clone from github or simply run the following dotnet new command in command prompt to create a new project from EISK:

Command to install EISK template in your machine: dotnet new -i eisk.webapi

Command to create a new project: dotnet new eiskwebapi -n Eisk

Once the contents are available, just open the created solution, select “Eisk.WebApi” as startup project and press F5!

That’s it!

What’s Next?

After running the created project successfully, you’ll get an understanding about how the sample use case has been used to explore cutting edge technologies for building a web api.

Next — you can try some hands-on experience by creating your own api on top of your custom entity and see how quickly you can roll out an enterprise quality web api with similar quality and productivity.

Utilities and code samples as provided in EISK have intentionally been designed to be self explaining. You may still want to get deeper understanding by exploring the documentations:

Enjoy!
Scheduled Background Tasks made easy with Elsa Workflows
By: Sipke Schoorstra
Tags: Elsa, Scheduled Tasks, Background Task, Workflow, Aspnetcore

Elsa Workflows

Elsa Workflows is an open source library for .NET that enables applications to implement both short-running and long-running workflows, either in code, using a designer, or both.

Even if you have zero interest in working with workflow systems and designers, Elsa comes with an easy to use API to implement background tasks.

The Elsa equivalent of a Hosted Service in .NET Core and a Job in Quartz.NET is the Workflow.

As a matter of fact, Elsa Workflows’ scheduling mechanism directly uses Quartz.NET to schedule work at a given time.

To implement a workflow, all you have to do is implement IWorkflow and register it with DI. That’s it.

For example, to implement a scheduled job, you could create the following workflow:

And then register it with DI like this:

services

.AddElsa()

.AddWorkflow<MyJob>();

Yep, that’s pretty easy.

Of course, most background jobs will do a little bit more than just printing the current date and time to the console. For example, you may want to clean out the trash every Monday morning at 08:00:

Looks pretty neat!

Not only does Elsa simplify declaring scheduled tasks with this simple API, it automatically opens the door for you to implement actual workflow stuff (since after all, this is a real workflow!).

For instance, after cleaning out the trash, you may want to sleep for a while, walk the dog and do some dishes, perhaps something like this:

Notice that in this version of the workflow, there are two time-based triggers:

Cron (which starts the workflow ever Monday morning at 08:00) Timer (which starts ticking after the trash has been cleaned).

Implementing this with Quartz.NET would require you to manually schedule a new job, possibly from some event handler raised by the clean up service. Doable, but increasingly harder to follow as complexity increases.

And of course it would be quite sad for the dog to be walked on Monday mornings only. Fortunately Elsa makes it easy to fix that by just declaring another workflow class that takes good care of the dog.

To learn more about Elsa, checkout the project on GitHub.

Summary

So there you have it! We looked at 3 viable options of implementing scheduled tasks in .NET Core / .NET 5.

The Hosted Service option is great for simple, recurring schedules and requires no external packages. But if you want cron schedules, you better pull up your sleeves and start writing some code.

Next, we looked at Quartz.NET, which I think is pretty awesome for implementing background tasks.

Finally, we looked at Elsa Workflows, which I think is another great choice to make implementing background tasks a real breeze. And being a workflow, it automatically enables you to implement more complex, long-running process flows, where you can mix & match any kind of trigger beyond time-based events. Examples include service bus messages, HTTP requests, application-specific events, and virtually anything you can dream up.
ASP.Net Core: Building a robust authentication and authorization system using IdentityServer
By: Vikas Sharma
Tags: Authentication, Identityserver4, Angular, Oidc, Aspnetcore

In this article, we will see the curious case of Authentication and Authorization using the Identity Server. We will touch upon the fancy terms like OAuth 2.0 and OpenID Connect. My goal through this article is to guide you all the messy process we have to go through while implementing the authentication and authorization. I will try my best to explain things in plain English.

What the heck is OAuth 2.0?

OAuth 2.0 is an authorization protocol that allows a user to grant 3rd party apps access to the user’s resources without actually revealing the user’s identity or credentials. The point to notice here is that it’s an authorization protocol and should be only used for authorization scenarios not for authentication workflow.

Why OpenID Connect?

OAuth 2.0 is very elegant in solving authorization problems but we needed a solution to handle user authentication use cases. Smart brains came together to build an efficient solution. OpenID Connect is an identity protocol built on the top of the OAuth 2.0 framework.

Say Hi to IdentityServer! 👋

IdentityServer is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core. IdentityServer is an officially certified implementation of OpenID Connect.

As per official documentation of IdentityServer, it has a number of jobs and features:

protect your resources

authenticate users using a local account store or via an external identity provider

provide session management and single sign-on

manage and authenticate clients

issue identity and access tokens to clients

validate tokens

The Hello World Program

In this tutorial, we will build a central authentication system that will handle the authentication request from an MVC and an angular app to access protected resources.

The Hello World Program

MVC app

Angular app

We will set up a central authentication system using IdentityServer. Then we will create an MVC app whose secured pages can be accessed after authentication by the authentication server. We will also create an angular app that would be able to access secured API after authentication.

The Source Code

You can find the complete source code

Steps required to set up the central authentication system — view from 1000 feets

Create MVC ASP.NET Core project

Add IdentityServer NuGet packages

Add EF Core NuGet packages to store clients and configuration

Configure IdentityServer Services in Startup

Add IdentityServer pipeline in the middleware

Seed Clients and Resources data in the Database

Create AccountController to handle Register and Login scenario

Setting up Authentication Server from ground up
Dependency Injection in ASP.NET Core
By: Kasthuri Gunabalasingam
Tags: Dependency Injection, Aspnetcore

Dependency Injection is the set of practices that allows to build loosely coupled applications. This is not a framework or tool, it is just a software design pattern, which is a technique for achieving loosely coupled mechanism among the software components.

ASP.NET Core framework contains a built-in Dependency Injection container it self. Prior to .NET Core, developers used Autofac, Ninject frameworks to achieve the Dependency injection.

public class HomeController : Controller

{

public IUserRepo _userRepo; public HomeController()

{

_userRepo = new MockUserRepo();

} public string Index()

{

return _userRepo.GetUser(1).Name;

}

}

Here HomeController has a dependency in IUserRepo ( an interface) and it’s implementation in MockUserRepo. HomeController is tightly coupled with MockUserRepo.

If any changes happens in MockUserRepo, HomeController need to be test again. In case IUserRepo decided to use another implementation (for example instead of MockUserRepo, use another implementation file called UserRepo), need to change all the controllers, which are using MockUserRepo dependencies. This is not an efficient way and difficult to manage as well. We can over come this issue using Dependency Injection in ASP.NET Core.

Let see how to achieve the dependency injection in ASP.NET Core.

public class HomeController : Controller

{

public IUserRepo _userRepo; public HomeController( IUserRepo userRepo)

{

_userRepo = userRepo;

} public string Index()

{

return _userRepo.GetUser(1).Name;

}

}

instead of creating dependency using ‘new’ keyword, inject IUserRepo in to the HomeController class using it’s constructor. To get IUserRepo implementation in to HomeController, we need to register the interface(IUserRepo) and it’s implementation(MockUserRepo) using ASP.NET Core Dependency Injection container in startup.cs file.

public void ConfigureServices(IServiceCollection services)

{

services.AddControllersWithViews();

services.AddSingleton<IUserRepo, MockUserRepo>();

}

you can find the source code here.
Part 1 Building an ASP.NET Core and Angular Application (Installation and configuration)
By: Victor Gabriel Bucar Freitas
Tags: Angular, Vscode, Web Development, Aspnetcore

I’m back!

After a long, long time without writing anything on the blog, I decided to write again. Not only to help those who are kind of lost or confused how all these technologies work and interact with each other, but also as a way to keep a record and repository of content and learning for me as well.

This time i would like to talk about two technologies that I like a lot, and that has very large communities and every day gain more followers. I’m talking about ASP.NET Core and Angular. So I’m preparing a series of post to demonstrate the use of these technologies and also several others like HTML5, CSS3, Node.js, Git, Bootstrap, SQLLite. Entity Framwork.

Although at the time of this post we already have the recent release of a preview of Asp.Net Core 3, and Angular is in version 7, we will use Asp.Net Core 2.1 and Angular Version 6. Both installation, concepts and applications that I will be using are still to be valid. So let’s get started without further delay.

1 — First things first, if you want to start developing with .NET the first thing to do is to install the .NET SDK (Software Development Kit) But what is it anyway?According to the definition of Microsoft’s own website “The .NET Core Software Development Kit (SDK) is a set of libraries and tools that allow developers to create .NET Core applications and libraries.” Said this, go to the microsoft website and install your SDK on this link . There you will find the installations for Windows, Linux and Mac.

2 — Install Node.js on the official website of node here. We will need it to work with our Angular projects. It already imports and brings several tools that we will use such as npm.

3 — Our Text Editor, with most of our tools installed we will need a text editor for our codes. I recommend using VS Code because it has many extensions that make it an excellent development tool, besides being the editor that I will use throughout this series of posts. Official Visual Studio Code Web Site

4 — Database, we will initially use an implementation with SQLLite, which is a super light weight database and is widely used. For this we will install the DB Browser, which is a graphical tool to manipulate our database. Download here

5 — Postman, this tool makes easier our tests with the API specially while we do not yet have an application to test the requisitions. Below I will leave two images with extensions that are used quite frequently. You need to install at least these selected extensions, but using the others in the image can make certain tasks easier. Download postman from here

That’s it for today. In the next post we will start our project by creating our API and the database. See you soon!
Part 1 Building an ASP.NET Core and Angular Application (Installation and configuration)
By: Victor Bucar
Tags: Aspnet Web Api, Angular 7, Web Development, Aspnetcore

I’m back!

After a long long time without writing anything on the blog, I’ve decided to write again. Not only to help those who are kind of lost or confused how all these technologies work and interact with each other, but also as a way to keep a record and repository of content and learning for me as well.

This time i would like to talk about two technologies that I like and work really well together, they have great comunities and every day more followers are joining them. I’m talking about ASP.NET Core and Angular.

I’m preparing a series of post to demonstrate the use of these technologies and also several others like HTML5, CSS3, Node.js, Git, Bootstrap, SQLLite. Entity Framwork.

Although at the time of this post we already have the recent release of a Asp.Net Core 3, and Angular is in version 7, we will use Asp.Net Core 2.2 and Angular Version 7. Both installation, concepts and applications that I will be using are still to be valid. So let’s get started without further delay.

1 — First things first, if you want to start developing with .NET the first thing to do is to install the .NET SDK (Software Development Kit) But what is it anyway?According to the definition of Microsoft’s own website “The .NET Core Software Development Kit (SDK) is a set of libraries and tools that allow developers to create .NET Core applications and libraries.” Said this, go to the microsoft website and install your SDK on this link . There you will find the installations for Windows, Linux and Mac.

2 — Install Node.js on the official website of node here. We will need it to work with our Angular projects. It already imports and brings several tools that we will use such as npm.

3 — Our Text Editor, with most of our tools installed we will need a text editor for our codes. I recommend using VS Code because it has many extensions that make it an excellent development tool, besides being the editor that I will use throughout this series of posts. Official Visual Studio Code Web Site

4 — Database, we will initially use an implementation with SQLLite, which is a super light weight database and is widely used. For this we will install the DB Browser, which is a graphical tool to manipulate our database. Download here

5 — Postman, this tool makes easier our tests with the API, specially while we do not yet have an application to test the requisitions. Below I will leave two images with extensions that are used quite frequently. You need to install at least these selected extensions, but using the others on the image can make certain tasks easier. Download postman from here

That’s it for today. In the next post we will start our project by creating our API and the database. See you soon!
ASP.NET CORE PROJECT FILE STRUCTURE PART-I — Sagar Jaybhay
By: Sagar Jaybhay
Tags: Aspnet, Sagar Jaybhay, Web Development, Aspnetcore

If you are using C# as a primary programming language then your project file extension is .csproj and if you are using VB as the primary language the .vbproj as a solution.

In the previous version, if we want to modify our project solution file we need to unload project then perform edit and then save and after this, we need to open this. But in this core, we no need to unload project and then edit you can directly do so.

In the previous version whatever you add in your project the reference of this is added to the project file means .csproj file but in this new version or core no references are added in project files.

1.(Target Framework Moniker)TFM:

This is TFM netcoreapp2.2.

This is used for how thee application is hosted which means InProcess or OutOfProcess.

In-process: In this host our asp app inside IIS worker process which uses w3wp.exe OutOfProcess: In this hosting model forward the web requests to back-end Asp.net core app which is running on a KESTREL server. By default is In-process hosting

Package Reference

Microsoft.AspNetCore . The app is used to manage or hold the list of dependencies. It is not added default references on its own but it holds the list of dependencies or other packages .

When we don’t specify the version the implicit version which is specified by SDK is taken.

Main Method in Asp.Net core:-

The Main method present in the program class is the entry point of an application.

At run-time hosting environment search for the Main method and it is a place where application kicks off. Asp.Net application initially starts as a console application.

So Main method is used to configure ASP.NET Core and start it and at that point, console application becomes a Web Application.

public class Program

{ public static void Main(string[] args)

{

CreateWebHostBuilder(args).Build().Run();

} public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); }

If you see above code Main method is called CreateWebHostBuilder and this method is called the startup class which is an extension method.

This CreateWebHostBuilder is used to create web host builder.

CreateWebHostBuilder Tasks:
Documenting additional API endpoints in Swagger in ASP.Net core
By: Nitesh Singhal
Tags: Swashbuckle, Api Documentation, Aspnetcore, Swagger

In a typical ASP.Net core WebAPI project when we want to expose an API, we create a controller and implement the API functionality.

But this is not always required, we can map endpoint without defining the controllers. for some trivial task or information you don’t need to create controller and implement the logic there.

for example, if I want to write an API which returns the version.

I can simply write code like this and call it.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

... app.UseEndpoints(endpoints =>

{

endpoints.MapControllers();

endpoints.MapGet("/version", context =>

{

var config = new { Version = "1.0"};

return context.Response.WriteAsJsonAsync(config);

});

});

}

when I call this endpoint from browser I get following result.

accessing version API from browser

API in Swagger UI

Let’s check if this new API is available in the swagger document or not. Open the swagger UI and we can see that this endpoint is not available in the swagger document. The main purpose of swagger document is to provide all the endpoints which are exposed by webapi, but this endpoint “version” is not listed.

So how do we add it ?

Adding API to swagger document

In this tutorial, we will add this API endpoint to swagger document so that it can be accessed via swagger UI also.

Let’s make the changes.

Add a class “CustomDocumentFilter” in your existing project which has already support for swagger. see below code.

and add following code to AddSwaggerGen method

services.AddSwaggerGen(c =>

{

c.DocumentFilter<CustomDocumentFilter>();

});

Let’s run the application.

You can see the newly added “Version” API.

let’s verify if it is working or not.

as we can see in screenshot the API response is shown correctly.

Summary

Adding any additional endpoint in swagger endpoint is very easy, just follow the same procedure for adding your own API.

Hope this is helpful..!

Let me know your thoughts below..!

If you liked this article please share the energy and press the clap button And follow me for more interesting articles like this one.
Running automatic tasks in ASP.Net Core WebAPI
By: Nitesh Singhal
Tags: Dotnet, Webapi, Scheduling, Aspnetcore, Background Service

Recently in one of the discussion for our WebAPI project we got into a scenario where we were suppose to update some value automatically without being triggered by any API.

The discussion left me wondering if this is possible in WebAPI project, so I decided to do some search and finally found a way of doing this by using background service in ASP.Net core WebAPI.

IHostedService and BackgroundService

In ASP.Net core, we can implement IHostedService interface to run background tasks asynchronously inside our application.

It provides to two methods “StartAsync” and “StopAsync”. as the name suggested these methods is used to start and stop the task.

ASP.Net core also provides abstract class “BackgroundService” which exposes only one method “ExecuteAsync” which executes continuously in background.

We can write our logic inside this methods so that it get executed in background.

In this tutorial I am going to show demo of backgroundservice implementation.

So let’s get started..

Sample example

Let’s take an example that I want to take backup of data at midnight.

Let’s see how we can achieve this with background service.

Create a new webapi project with visual studio and add the following class.

Now open Program.cs and add the following code to CreateHostBuilder method.

...

.ConfigureServices(services =>

{

services.AddHostedService<WorkerService>();

});

Build the project and run.

You will see the task getting executed without any external trigger from any API.

Console window showing execution of background task

Summary

Background task will be required for many use cases like if you want to take backup or trigger a specific task at certain time or if you want to refresh cache or something else.

For simple background task you can use this technique, but for more complex scenarios you can make use of libraries like Quartz and Hangfire where task management is easy.

Hope this is useful.

Let me know your thoughts below..!
Multiple implementations of one interface using asp.net core dependency injection
By: Amir Jalali
Tags: Software Engineering, Programming, Aspnetcore, Software Development, Dependency Injection

Dependency Injection

Suppose that you have different SMS provider and you want to choose between one of these providers based on some criteria.

There are two ways that you can choose which implementation of an interface get instantiated using your IOC of choice.

The first approach which I won’t recommend is by registering your services and selecting the one that you want at runtime.

services.AddSingleton<ISmsProvider, SmsProviderA>();

services.AddSingleton<ISmsProvider, SmsProviderB>();

services.AddSingleton<ISmsProvider, SmsProviderC>();

Then at runtime you could resolve the correct object by doing

var services = serviceProvider.GetServices<ISmsProvider>();

var smsProviderC= services.First(o => o.GetType()== typeof(SmsProviderC));

The problem with this approach is that when we call serviceProvider.GetServices<ISmsProvider>();

all of the services will get instantiated not just the one that you want so SmsProviderA , SmsProviderB and SmsProviderC will be instantiated and if these services also have many dependencies inside, all of those dependencies also will be instantiated.

So, consider this approach if your services are lightweight or if they don’t have any dependencies inside.

The second approach which I recommend is as follow first define your interface

public interface ISmsProvider

{ Task<SendResult> SendSmsAsync(string to, string message); }

Then implement your services
CORS in ASP.net Core 2.x
By: Hidayat Arghandabi
Tags: Cors, Aspnetcore, Error

What is CORS

According to the MDN documentation, Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

An example of a cross-origin request: The frontend JavaScript code for a web application served from http://domain-a.com uses XMLHttpRequest to make a request for http://api.domain-b.com/data.json .

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers.

How to turn off the CORS

Turning off CORS is not a good practice, but sometime for a rapid development you may use different servers for you back end and front end.

In Asp.net Core 2.1 you place the below code in the Configure method.

// Cors Middleware

app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());

app.UseAuthentication();

app.UseMvc();

I wish this small article helps to turn your CORS
Fluent Validation in ASP.NET Core
By: Mukesh Murugan
Tags: Fluent Validation, Validation, Aspnetcore

When it comes to Validating Models, aren’t we all leaning towards Data Annotations? There are quite a lot of serious issues with this approach for a scalable system. There is a library, Fluent Validations that can turn up the validation game to a whole new level, giving you total control.

The Problem

Data Validation is extremely vital for any Application. The GO-TO Approach for Model validation in any .NET Application is Data Annotations, where you have to declare attributes over the property of models. Worked with it before?

public class Developer

{

[Required]

public string FirstName { get; set; }

[Required]

public string LastName { get; set; }

[EmailAddress]

public string Email { get; set; }

[Range(minimum:5,maximum:20)]

public decimal Experience { get; set; }

}

It is fine for beginners. But once you start learning clean code, or begin to understand the SOLID principles of application design, you would just never be happy with Data Annotations as you were before. It is clearly not a good approach to combine your models and validation logic.

With the implementation of Data Annotations in .NET Classes, the problem is that there will be a lot of duplication lines of code throughout your application. What if the Developer Model class is to used in another application/method where these Attribute validation changes? What if you need to validate a model that you don’t have access to? Unit testing can get messy as well. You will definitely end up build multiple model classes which will no longer be maintainable in the longer run. So, what’s the solution?

Introducing Fluent Validation — The Solution

Fluent Validation is free to use .NET validation library that helps you make your validations clean, easy to create, and maintain. It even works on external models that you don’t have access to, with ease. With this library, you can separate the model classes from the validation logic like it is supposed to be. It doesn’t make your Model classes ugly like Data Annotations does. Also, better control of validation is something that makes the developers prefer Fluent Validation.

Fluent validations uses lamba expressions to build validation rules.

For small systems, I would recommend just using Data Annotations, because they’re so easy to set up. For larger, more complex systems, I would recommend separating the validation concern using validator objects with Fluent Validation.

Read the complete article here — https://www.codewithmukesh.com/blog/fluent-validation-aspnet-core/
Logging and Debugging ASP.NET Core with Application Insights pt.1
By: Paul Lorica
Tags: Programming, Microsoft, Csharp, Aspnetcore, Azure

Series Part 1 Setting up App Insights and Viewing Logs

App Insights gives us the ability to view information about our app like Requests, Log Traces, Exceptions, Performance metrics, etc. Its honestly pure magic to me and one easiest and best ways to help you debug your Web App.

We’ll start with the basics here. Let's hook up a basic ASP.NET Core Web API with Application Insights.

Create an Application Insights resource

We will start off by creating the App Insights resource in Azure.

In the Azure Portal, create the application insights resource. If you are a newbie to Azure or just need more information refer to this document https://docs.microsoft.com/en-us/azure/azure-monitor/app/create-new-resource

I usually create and name an App Insights Resource for each stage of the development process.

So I follow the convention of {app-name}-{environment}

For example I would create 4 individual instances

AspNetCoreAppInsightsSeries-local

AspNetCoreAppInsightsSeries-development

AspNetCoreAppInsightsSeries-staging

AspNetCoreAppInsightsSeries-production

For now, we really just need AspNetCoreAppInsightsSeries-local as we will just run the API locally.
Secure ASP.NET Core Web API using API Key Authentication
By: Rred Cat
Tags: Hmac, Webapi, Aspnetcore, Mvc, Aspnet

I am implementing the simple web service that grants access via usual login and API login with a token. I have googled a bit for the right solution but found it for ASP.NET MVC 5 application only (original article — Secure ASP.NET Web API using API Key Authentication — HMAC Authentication).

So it is something that helps me to do the same stuff for ASP.NET Core that I am using for my web service.

First of all, I went through great workshop related to the various new pieces in ASP.NET Core Authorization — AspNetAuthorizationWorkshop. Aslo, check out the great article about Filters.

However both these materials are focused on Authorization, it is nice to know, but for our purpose, we have to use Authentication.

I implemented custom AuthenticationHandler and overrode there HandleAuthenticateAsync. I returned AuthenticateResult.Success when request met requirement and AuthenticateResult.Fail in otherwise.

When handler was implemented I needed to configure service to use it. I wrote next code in Startup.ConfigureServices method:

Startup.cs

And marked controller/action that I needed to protect:

Vu’a la, it works now.



Pay attention: you could read once the body in request pipeline; it is empty during the second reading. AuthenticationHandler reads body for computing hash, so model binder can’t process correct binding from request.body to post or put parameters. However, this bug is easy to fix by enabling rewind for body stream (Allow rewind request.EnableRewind(); and rewind request.Body.Position = 0; in my code).

I used AddMvcCore() rather AddMvc() for better performance. Also, I added AddJsonFormatters for exploring JSON in respoce and AddAuthorization to use security.

You could find source there on GitHub.

Be aware; this code isn’ t production-ready because it is exposed to replay attack. You have to implement expiration date in your key.
Tool-Tip in ASP.NET Core using Kendo UI Component
By: Abhishek Dabhi
Tags: C Sharp Programming, Development, Aspnetcore, Tooltips, Kendo Ui

Introduction

Tool-tip replaces native tool-tips, making them theme-able as well as allowing various customization. This article will explain you how to set up Tool-tip using Kendo UI component and Tag Helper.

Tag Helper with Various Attributes

When working within a View Page, Tag Helpers and Html Helpers can be used to retrieve translations. When possible, it is best practice to use Tag Helpers over Html Helpers. Html Helpers should be used only in situations where Tag Helpers won’t work.

Note: To use the Tool-tip with styles and functionalities, we need to create the relative style-sheet and JavaScript files.

First of all, add Tag Helpers in *.cshtml file to create tool-tip as below:

<tooltip message-key=''/>

Tool-tip tag has following attributes :

message-key

‘message-key’ attribute with key, is mandatory to create tool-tip. The value should be key from ‘Message.resx’ file that will get value of the key and show on Web page in tool-tip.

<tooltip message-key='cannotAddRow'/>

class-icon

‘class-icon’ is an optional attribute. It is used to change the tool-tip icon on web-page. By default, it shows icon of Information from font-awesome icons. If you want different icon from that then you can add this attribute and add icon class name as a value that will change the icon of tool-tip. For Instance :

<tooltip message-key='' class-icon='fas fa-question-circle'/>

size

‘size’ is an optional attribute. It is used to change tool-tip icon’s size. It will be change in only ‘pixel’ abstract unit. By default, it is ‘12’ px. It will only take an integer in attribute value. For Instance :

<tooltip message-key='' Size='15'/>

label-title

‘label-title’ is an optional attribute. It is used to give tool-tip a title. If you don’t give any title to tool-tip, it will show ‘Information’ as a title by default. You can change label to add this attribute with proper key from ‘Label.resx’ file. For Instance :

<tooltip message-key='' label-title="all"/>

auto-hide

‘auto-hide’ is an optional attribute. It has a Boolean value either ‘true’ or ‘false’. ‘true’ is by default which Specifies if the Tool-tip will be hidden when the mouse leaves the icon. If it sets to ‘false’, tool-tip displays even if the icon is no longer hovered and until a Close button will be clicked which is shown on the top-right side within Tool-tip. For Instance :

<tooltip message-key='' auto-hide='false'/>

position-attr

‘position-attr’ is an optional attribute. It is used to set up the position of the Tool-tip. It has four different sides that you can specify in the attribute value: Right, Left, Top, Bottom. By default, it sets to the Right side, but you can change position with this attribute. For Instance :

<tooltip message-key='' position-attr='Top'/>

Please let me know if there is any questions or concerns about this article and please like and share to help others!
Inter-AWS Lambda Communication in ASP.NET Core
By: Igor Krupin
Tags: AWS, AWS Lambda, Api Gateway, Aspnetcore

Enabling Request-Response and Async communication between ASP.NET Core applications deployed as AWS Lambdas

You have a flock of ASP.NET Core applications deployed as AWS Lambdas and you need to enable communication between them. You need to support sync (request-response) and async patterns (fire-and-forget).

AWS provides a handy AmazonLambdaClient class as part of the AWSSDK.Lambda library that enables you to Invoke one lambda from another (or from anywhere, really). You can invoke from outside the VPC as well, provided you have the proper creds and region info.

To keep things simple, we’ll assume your lambda are deployed behind an API Gateway. The code sample will work with ALB lambdas with slight modifications.

You can read more about Lambda invocation here: https://docs.aws.amazon.com/lambda/latest/dg/lambda-invocation.html

AWS does not publish the inner working of the Invoke command, but it’s likely the traffic does not leave AWS when invoked from within. It is also likely the traffic bypasses WAF (if you have it setup). This needs to be confirmed via further testing.

Why not simply make HTTPs restful calls, at least for the sync flow? What does Invoke bring to the table?

First, some choose to deploy a private API Gateway with VPC endpoints precisely for inter-microservice communication. This ensure the traffic does not leave the VPC, and also does not needlessly transit though WAF and Shield which may throw a false-positive and deny some requests. The private API Gateway takes cycles to set up and maintain, and VPC enpoints cost you.

Second, you need to deal with URLs. URLs for PROD, PRE-PROD, and so on.

Lastly, you still have async to worry about which necessitates things like SQS or SNS, etc.

With AmazonLambdaClient, you just need to know the name of the function you are trying to call, and the region it’s in. That’s it. AWS will figure out the rest. You can either Invoke() or InvokeAsync() if you need async flow.

For async flow, AWS will post the request on an internally-created queue and will then attempt to deliver the message. Once again, async is a bit of a black box but AWS does shine some light on the implementation. You get “at-least-once” delivery, you can configure the Retry policy, and any undelivered messages will land on the DLQ. From this we can surmise that SQS is used in the background to power the async flow.

Async may not be perfect: maximum time within which AWS will attempt to deliver your messages has a limit, and the frequency and the number of retry attempts is undocumented. That said, it’s not a bad option and may suffice in many scenarios.

On to the code!

You can set the stage name in the request (for API Gateway requests), and you can retrofit the code in the event you are fronting your Lambdas with ALBs.

When the request hits the ASP.NET Core pipeline all the regular filters and middleware kick in. So if you have AuthZ/N enabled you need to ensure the caller attaches the appropriate creds when making the call to another lambda.

Enjoy Responsibly.
Scalable scenario to configuring Entity Framework DbContext(ASP.Net Core 3.x & MSTest) and creating a flexible Startup class
By: Tarek Najem
Tags: Option Pattern, Mstest, Entity Framework Core, Factory Pattern, Aspnetcore

When we are configuring the DbContext in an ASP.NET Core web application, we typically use AddDbContext extension method as follows:

If we take a closer look at the parameter of the AddDbContext extension method, we’ll find that is an action, and through an Action, we can encapsulate a method , delegate, in-line delegate, lambda or etc.

In this case, the Action must construct the DbContext options.

What interests us most is configuring the DbContext according to the our configuration ‘{environment}settings.json’.

How do we implement this scenario and why?

The answer to the question why would we do this:

We want to dramatically simplify and improve the experience for configuring DbContext and make them truly composable, where we can try to create a flexible scenario that automatically configures DbContext so that it can encapsulate a complete feature and provide an instant utility without having to go through various steps on how to manually configure it in different places in the Startup configuration class.

From this point on, we will try to figure out how to implement this scenario and try to simplify all the concepts that we will encounter.
How to configure Swagger UI in ASP.NET Core API-
By: Antariksh Verma
Tags: Api Documentation, Net Core, Aspnetcore, Dotnet Core, Swagger

In this article, we are going to cover how to configure Swagger UI in an ASP.NET Core Web API application.

What is swagger /Open API-

When developer consume API, It is very crucial to understand how to use it and what are the different types of methods present in the it along with some other information like request response and so on. A detailed documentation is required to expose these type of information.

Here Swagger comes into the picture, it is an excellent tool that helps to generate API documentation.

Now let’s start to configure the Swagger in ASP.NET Core API-

I am assuming that you have already created ASP.NET Web API application. Now we are going to follow the below steps-

1. Install Swashbuckle.AspNetCore -

Right click on the project and go to “Manage NuGet Packages” >> type “Swashbuckle.AspNetCore” >> install “Swashbuckle.AspNetCore” package.

There are three main components of the swashbuckle package-

a. Swashbuckle.AspNetCore.Swagger — It contains the middle ware to expose Swagger JSON endpoints from API.

b. Swashbuckle.AspNetCore.SwaggerUI — It builds the rich UI for providing the information of various API methods from the swagger JSON.

c. Swashbuckle.AspNetCore.SwaggerGen — It builds the swagger document object from API routes, controllers and models.

2. Configure the Swagger middleware-

· Open “Startup.cs” file and add the following code in “ConfigureServices” method-

· Add the following code in “Configure” method

Now it’s time to execute and run the API to see swagger documentation. Press ctrl+ F5 and add “/swagger/index.html” in your API URL.

Here we go, we can see an interactive UI which consist of all the endpoints in our application.

Now, you can directly hit and test your API using the swagger UI.

I hope that it will help you to configure swagger and document your API.

Any questions, comments or suggestions are highly appreciated!

Thank you !!