European ASP.NET 4.5 Hosting BLOG

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

European ASP.NET Core Hosting :: Non-Nullable Property Must Contain A Non-Null Value

clock December 21, 2021 06:51 by author Peter

Recently, I was getting this warning for most of the properties which are not specified as nullable. I was not happy with this warning, though I was able to run my .NET 6 application smoothly.

Exact Error:
    Non-nullable property ‘propername’ must contain a non-nullvalue when exiting constructor. Consider declaring the property as nullable

Non-nullable property must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

After carefully observing this error message, it makes sense for those properties. In order to minimize the likelihood that our code causes the runtime to throw System.NullReferenceException, we need to resolve this warning.

Therefore, the compiler is giving warning in the solution that the default assignment of your properties (which is null) doesn’t match its state type (which is non-null string

https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references

We can resolve this error in 3 ways.

Solution 1

We can simply make the properties nullable, as shown below:
public class AppSetting {
    public string? ReferenceKey { get; set; }
    public string? Value { get; set; }
    public string? Description { get; set; }
}

Solution 2
We can assign a default value to those properties as shown below:
public class AppSetting {
    public string ReferenceKey { get; set; } = “Default Key”
    public string? Value { get; set; } = “Default Value”
    public string? Description { get; set; } = “Default Description”
}

Alternatively, you can give a reasonable default value for non-nullable strings as string.empty.

Solution 3
You can disable this warning from project level. You can disable by removing the below line from project file csproj or setting.

<Nullable>enable</Nullable>

Reference: https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references#nullable-contexts

These are three ways you can overcome the above warning.

HostForLIFE.eu ASP.NET Core 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.




European ASP.NET Core Hosting :: Custom Controls In C#

clock December 20, 2021 08:14 by author Peter

Custom controls are control that are created by user when Windows Forms controls do not fulfill their application requirements. Simple custom controls can be created by inheriting the Control class, UserControl class, or any Windows Forms controls. The developer should write the code for the custom control in the OnPaint event of the control. After writing the code, it should be saved with the .cs extension. The code can be complied into an assembly and saved into the application’s directly by executing the following command:

Syntax
csc /t:library/out:<path to your application;s directory>/<name of the assembly that contains the custom control class> /r:System.dll
/r: System.Windows.Form.dll /r: System.Drawing.dll <name of the custom control class file>

Where,
    /t:library, Instructs the compiler that the assembly that is being created is a library and it is cannot be executed.
    /out : Specifies the name and path of the assembly file that contains the custom control.
    /r: Specifies the names of all the assemblies that are used by the code.

Control Class

The Control class includes functionalities to handle user input, define position and size of controls, and so on. The control class can be inherited by other classes to display information to the user. The properties of Control class.

    Bounds
    Specifies or retrieves the size and location of the specified control with respect to its parent control.
    CanFocus
    Retrieves a value that indicates whether the specified control can receive focus.
    CanSelect
    Retrieves a value that indicates whether the specified control can be selected.
    Created
    Retrieved a value that indicates whether the specified the specified control has been created.
    Dock
    Specifies or retrieves the control borders, which are docked to its parent control. It also identifies the way a control is resized with its parent.
    Left
    Retrieves the distance between the left edge of specified control and the left edge of the container’s client area.
    Right
    Retrieves the distance between the right edge of specified control and the left edge of the container’s client area.
    TabIndex
    Specifies or retrieves the tab order of the specified control within a container.

Table below the list of methods of control class.

Method Description
Contains specifies control is a child of the control
CreateControl Forcibly creates a control along with its handle and child controls.
CreateGraphics Creates a graphic for the specified control.
GetNextControl It retrieves the next control according to the specified tab order of child controls.
GetPreferredSize It retrieves the size of the rectangular area.
Hide Hides the specified control from the user.

Below are the lists of events of Control class.

Event Description
ControlAdded Occurs when a new control is added to a collection of controls.
ControlRemoved Occurs when a specified control is removed from a collection of controls.
Validated Occurs when the validation process of the specified control is complete.

Code below creates a rectangular custom control and changes its appearance when the control is validated.

public partial class CustomControl: Control {
    Graphics graphics;
    protected override void OnPaint(PaintEventArgs pe) {
        this.Bounds = new Rectangle(15, 15, 30, 15);
        if (this.CanFocus) {
            this.Focus();
        }
        this.Dock = DockStyle.None;
        graphics = this.CreateGraphics();
        graphics.FillRectangle / (Brushes.CornflowerBlue, ClientRectangle);
    }
    protected override void OnValidated(EventsArgs e) {
        graphics.FillRectangle(Brushes.MediumOrchid, ClientRectangle);
        graphics.DrawRectangle(new Pen(Color.Black, ClientRectangle);
    }
}

In this code, the custom control is created by inheriting the Control class. When the OnPaint() method is invoked, the Bounds property is used to set a rectangular region. This is done by invoking the constructor of the Rectangular class, which takes the x and y coordinates, width and height as the parameters. The CanFocus property is used to check whether the control can receive focus. By default, it returns true and the focus() method is used to focus the control. The dock style for the control is set to None, which means that control cannot be dragged to some other location on the form. The graphics object Brush, is used to create the custom control within the specified rectangular bounds. When the validations are successfully made to the control, the OnValidated() method is invoked. This event changes the appearance of the control by changing its back color and border color.

The following code demonstrates how to override the Text and BackColor properties of the Control class. This is useful in setting the default values of the properties when the custom control appears on the form.

The Text property of the Control class is overridden. The BackColor property is also overridden to set the default color as dark blue. When the custom control is added to the form, the control appears with dark blue as the background color and customLabel as the default text. This text and background color appear on the label due to the Invalidate() method, which in turn, calls the OnPaint() method. This method redraws the control within the given client area along with the specified text and background color.
UserControl Class

The UserControl class allows the user to create controls that can be used in many places within an application of across multiple applications.


Table shows the properties of UserControl class

Property Description
AutoSizeMode Specifies or retrieves the way a control will resize itself.
AutoValidate Specifies or retrieved the way a control performs validation when the focus is switched to another control
HorizontalScroll Retrieves the characteristics of the horizontal scroll bar.
VerticalScroll Retrieves the characteristics of the vertical scroll bar.

Table below the methods of UserControl class.

Method Description
PerformAutoScale Performs automatic scaling of the specified container control and its child controls.
ScrollControlView Scrolls the specified control into view.

Table shows the events of UserControl class.

Event Description
AutoValidateChanged It occurs when the value of AutoValidate property is changed.
Load Before the specified control becomes visible for the first time.

Code below shows how to create custom scroll bars using the UserControl class.

public partial class ScrollControl: UserControl {
    protected override void OnPaint(PaintEventArgs e) {
        this,
        VerticalScroll,
        Visible = true;
        this.HorizontalScroll.Visible = true;
        this.PerformAutoScale();
    }
    private void ScrollControl_Load(object sender, EventArgs e) {
        this.VericalScroll.Minimum = 0;
        this.VerticalScroll.Maximum = 100;
        this.HorizontalScroll.Minimum = 0;
        this.HorizontalScrollMaximum = 60;
    }
}


The OnPaint() method is invoked to set the vertical and horizontal scroll bars. This is done using the VerticalScroll and HorizontalScroll properties of the UserControl class. The PerformAutoScale() method automatically scales the control and its container control. When the created custom control is loaded, the Load event is raised. When this event is raised, the Minimum and Maximum properties sets the minimum and maximum limits for both the scroll bars.
Control Type Recommendations

Windows Forms provide the user with a variety of options while working with controls. The user can either use the Windows Forms controls or create a new control. But, sometimes, the user might get confused about the type of control to be used in the application. The difference between various types of controls from which the user can inherit are listed as follows:

Inheriting Windows Forms Controls
Inheriting Windows Forms controls allows the user to implement the functionalities of the inherited control. The user can also extend the functionalities of the inherited control. The user can inherit from the Windows Forms control if the inheriting control fulfills most of the application’s requirements.

Inheriting the Control Class

The user can inherit from the Control class while customizing the appearance of the control. Also, inheriting the control class allows the user to implement the functionalities that are not provided by the standard controls.

Inheriting the UserControl Class
When the user wants to combine the functionalities of several Windows Forms controls, a user can create a composite control by inheriting the UserControl class.

Property- Changed Events

Windows Forms allows the user to send notifications when the value of the property is changed. The user can send notifications by defining an event and then a method that raises the event. The event name is the name of the property by appending the word, Changed, to the name of the property. For example, if the name of the property is BackColor, the user can define an event named BackColorChanged and the event-handler method named OnBackColorChanged.

Event handlers can be created to respond to property- change events. This allows developers to define various actions that can take place when a property of the control is changed.

Code below creates a custom TextBox control and raises an event when a value in the control is changed

public partial class TxtPrincipal: TextBox {
    int years;
    float rate;
    double principal;
    double interest;
    protected override void OnTextChanged(EventArgs e) {
        years = 10;
        rate = 8.5 F;
        principal = 0;
        interest = 0;
        try {
            principal = Convert.ToDouble(this.Text);
            interest = (principal * years * rate) / 100;
            this.Parent.Text = ”Interest is: ”+interest.ToString();
        } catch (Exception ex) {
            MessageBox.Show(“Enter the numeric value only.”, ”ABCDBank”, MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.Focus();
        }
    }
}

In this code, a custom textbox namely, TxtPrincipal is created. The OnTextChanged event is overridden and is raised when the value in the control is changed. The code calculated the interest using the values specified in the control.

User-defined controls can be created by inheriting the control class. UserControl class, or any windows forms existing control’s class. The HorizontalScroll and VerticalScroll properties of the UserControl class can be used to define custom scroll bars. The GetImage() method of the ToolBoxBitmapAttribute class retrieves the image icon associated with the custom control. Composite controls are user controls that are created using one or more Windows Forns controls. Property-changed events allows the user to send notification whenever the value of the property is changed.

HostForLIFE.eu ASP.NET Core 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.

 



European ASP.NET Core Hosting :: The Downsides Of Using The Repository Pattern

clock December 13, 2021 06:46 by author Peter

The Repository Pattern is one of the most popular design patterns used for abstracting the data persistence in the database or retrieving from the database. The fundamental objective of the Repository Pattern is to help you decouple the data access and business logic layers of an application.

In this article, we’ll discuss the Repository Pattern. We'll learn why it is considered an anti-pattern and when we can use it in applications. Also, we'll illustrate its implementation with code examples in C#.

Let’s start.

Pre-requisites

You’ll need the following tools to deal with code examples,

    Visual Studio 2019 Community Edition (download)
    SQL Server 2019 Developer Edition (download)
    Entity Developer (download)

The Community Edition of Visual Studio 2019 and the Developer Edition of SQL Server 2019 are free editions. Entity Developer offers a fully functional 30-days Free Trial which we’ll use in our scenarios.
What is a Repository Pattern and Why We Should Care?

A Repository Pattern is a design pattern used to decouple the application's business logic and data access layers.

It was first introduced as part of Domain-Driven Design in 2004. Since then, it has become very popular. Now, it is the design pattern of choice for abstracting calls from the application to the underlying database.
But why is Repository Pattern so essential?

A repository, in essence, acts as a bridge between your application's domain and data mapping layers. When used correctly, it improves testability, code extensibility, and maintenance. With the Repository design pattern applied, the business logic layer of the application does not need to understand how data persistence works beneath the surface.

In other words, a repository abstracts the data storage and retrieval mechanism from the application.

This isolation enables the developers to focus on the business logic components rather than write boilerplate code to perform CRUD operations against databases. It also helps in unit testing the application's code since the business logic code is abstracted from the data access logic. You can change the data access code without impacting the work of the application works.

Assume that you introduce new database objects (tables, stored procedures, etc.). You can create a corresponding entity class in your application and write a few lines of data mapping code. You might (though, rarely) also need to change the database type altogether (from Oracle to SQL Server, PostgreSQL, etc.).

By leveraging the Repository Pattern, you can build and test the data access logic and the business logic of an application separately. It helps you to adhere to the Don't Repeat Yourself (DRY) principle since you don't need to repeat the code for performing CRUD operations.

In that case, you would need to change your data access code – update the repository classes. You might also want to change a few lines of code in the application, but that would be minimal.

What is an Anti-Pattern?
An anti-pattern is usually an ineffective solution to a problem. Anti-patterns are ineffective programming techniques that create issues rather than solve them and emerge due to over-engineering, incorrect application of design patterns, not following recommended practices, etc. On the other hand, anti-patterns are recurring solutions to common software application problems. Some common examples are spaghetti code, dead code, God object, etc.

The objective observation of functional and non-functional requirements will help you choose correct application patterns, frameworks, and platforms. You might not select a design pattern simply because you saw someone else use it or because someone told you there was no harm in using it. But an anti-pattern can help you determine the appropriate pattern you can use for your problem statement and available solutions.
An Extra Layer of Abstraction

One of the biggest downsides of the Repository Pattern is adding an extra layer of abstraction which eventually can become overkill for your application. Besides, you would typically need to create a repository for each entity in your application.

Things deteriorate as you include additional methods and complex search capabilities in your repository. You'll wind up with a repository that closely matches the permanent storage layer in use underneath. As an example, you might need methods such as FindProductById, FindCustomerById, etc. Such methods are present in the mature ORM frameworks. It implies that you are creating an abstraction on top of another abstraction for no good reason.
Downsides of a Generic Repository

In an application, the domain model and the persistence model have separate roles. The domain model’s behavior deals with real-world issues and solutions. The persistence model serves to represent how the application's data is saved in the data storage.

The Repository Pattern should encapsulate the persistence logic and conceal the underlying implementations of the data storage ways. The operations in repositories should be expressive rather than generic.

For instance, you cannot have a Generic Repository containing operations that you may use in any situation. As a result of this needless abstraction, the generic repository design becomes an anti-pattern.

A Generic Repository does not provide a meaningful contract. Therefore, you need to create a specific repository that extends the Generic Repository and offers a precise set of operations relevant to that particular entity.
Create a new ASP.NET Core Web API Project

Earlier, we mentioned the necessary tools to proceed to the practical scenarios. The time has come to use those tools.

First, we need to create a new ASP.NET Core Web API project,

    Open Visual Studio 2019.
    Click Create a new project.
    Select ASP.NET Core Web Application and click Next.
    Specify the project name and location to store that project in your system. Optionally, checkmark the Place solution and project in the same directory checkbox.
    Click Create.
    In the Create a new ASP.NET Core Web Application window, select API as the project template.
    Select ASP.NET Core 3.1 or later as the version.
    Disable the Configure for HTTPS and Enable Docker Support options (uncheck them).
    Since we won’t use authentication in this example, specify authentication as No Authentication.
    Click Create to finish the process.

We’ll use this project in this article.
A Generic Repository is an Anti-Pattern

You can take advantage of the Entity Developer tool to generate the Entity Data Model and repository classes. Using this tool simplifies the tasks significantly.

Select the project that we have created earlier. Specify Repository and Unit of Work as the code generation template when creating the Entity Data Model:

This would generate the Irepository and IProductRepository interfaces, and the EntityFrameworkRepository (the generic repository) and ProductRepository classes. It would also generate the entity classes and the unit of work classesandinterfaces.

The Generic Repository generated by Entity Developer would look like below:

public partial class EntityFrameworkRepository < T > : IRepository < T > where T: class {
    private DbContext context;
    protected DbSet < T > objectSet;
    public EntityFrameworkRepository(DbContext context) {
        if (context == null) {
            throw new ArgumentNullException("context");
        }
        this.context = context;
        this.objectSet = context.Set < T > ();
    }
    public virtual void Add(T entity) {
        if (entity == null) {
            throw new ArgumentNullException("entity");
        }
        objectSet.Add(entity);
    }
    public virtual void Remove(T entity) {
        if (entity == null) {
            throw new ArgumentNullException("entity");
        }
        objectSet.Remove(entity);
    }
    public DbContext Context {
        get {
            return context;
        }
    }
}

The code generator will generate the IRepositoryinterface as well:
public partial interface IRepository < T > {
    void Add(T entity);
    void Remove(T entity);
}

You can register an instance of the EntityFrameworkRepositoryclass as a scoped service to use it in the controller classes or elsewhere in the application.

public void ConfigureServices(IServiceCollection services) {
    services.AddScoped < IRepository < Product >> (x => {
        return new EntityFrameworkRepository < Product > (new DataModel());
    });
    services.AddControllers();
}

Now, you can use the dependency injection in your controllers to retrieve this instance.

The Generic Repository works fine as long as you perform simple CRUD operations. If you need specific methods, such as GetAllExpiredProducts, you’ll have to write a custom code in the ProductRepositoryclass. The generated class would look as follows:

public partial class ProductRepository {}

Here you have to write your own implementation of the GetAllExpiredProducts.

So, besides the generic repository that you can use in simple cases only, you'll always need specific repository classes for each entity class in your application to address such issues.

Use the Repository Pattern for applications that don’t perform complex operations.
Summary

In this article, we've discussed the pros, cons, and some common pitfalls you may face when using the Repository Pattern. Hope this information will be helpful in your further work.

HostForLIFE.eu ASP.NET Core 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.

 




European ASP.NET Core Hosting :: Deserialize JSON Format In An ASP.NET GridView Using System.Text.Json Library

clock December 7, 2021 08:03 by author Peter

JSON is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute-value pairs and arrays.

About System.Text.Json
System.Text.Json library provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.

Now, let's install and use JSON library in the ASP.NET website.

Install System.Text.Json library from NuGet
To install library, go to "Microsoft Visual Studio 2022" => "Tools" menu => "NuGet Package Manager" => "Manage NuGet Packages for solution", search for "System.Text.Json" and click "Install" as in below picture.

What is JSON Deserialization?
Deserialization is the process of parsing a string into an object of a specific type. The JsonSerializer.Deserialize() method converts a JSON string into an object of the type specified by a generic type parameter.

Below is the JSON format that will be used as an example:
string JsonString = @"{
        ""Version"": 1,
        ""Key"": ""314929"",
        ""Type"": ""City"",
        ""Rank"": 30,
        ""LocalizedName"": ""Stockholm"",
        ""EnglishName"": ""Stockholm"",
        ""PrimaryPostalCode"": """",
        ""Region"": {
            ""ID"": ""EUR"",
            ""LocalizedName"": ""Europe"",
            ""EnglishName"": ""Europe""
        },
        ""Country"": {
            ""ID"": ""SE"",
            ""LocalizedName"": ""Sweden"",
            ""EnglishName"": ""Sweden""
        },
        ""TimeZone"": {
            ""Code"": ""CET"",
            ""Name"": ""Europe/Stockholm"",
            ""GmtOffset"": 1.0,
            ""IsDaylightSaving"": false,
            ""NextOffsetChange"": ""2022-03-27T01:00:00Z""
        },
        ""DataSets"": [
            ""AirQualityCurrentConditions"",
            ""AirQualityForecasts"",
            ""Alerts"",
            ""DailyPollenForecast"",
            ""ForecastConfidence"",
            ""FutureRadar"",
            ""MinuteCast"",
            ""Radar""
        ]
 }";

And here are Class Properties for converting JSON string,

public class Cities {
    public int Version {
        get;
        set;
    }
    public string Key {
        get;
        set;
    }
    public string Type {
        get;
        set;
    }
    public string EnglishName {
        get;
        set;
    }
    public Region Region {
        get;
        set;
    }
    public Country Country {
        get;
        set;
    }
    public TimeZone TimeZone {
        get;
        set;
    }
    public string[] DataSets {
        get;
        set;
    }
}
public class Region {
    public string ID {
        get;
        set;
    }
    public string LocalizedName {
        get;
        set;
    }
    public string EnglishName {
        get;
        set;
    }
}
public class Country {
    public string ID {
        get;
        set;
    }
    public string LocalizedName {
        get;
        set;
    }
    public string EnglishName {
        get;
        set;
    }
}
public class TimeZone {
    public string Code {
        get;
        set;
    }
    public string Name {
        get;
        set;
    }
    public float GmtOffset {
        get;
        set;
    }
}

Now, the following is JsonSerializer.Deserialize() method to convert JSON string, which will be added to a datatable to use it in the GridView.

Cities cities = JsonSerializer.Deserialize<Cities>(JsonString);
int Version = cities.Version;
string Key = cities.Key;
string Type = cities.Type;
string City = cities.EnglishName;
string Region = cities.Region.EnglishName;
string Country = cities.Country.EnglishName;
string TimeZone = cities.TimeZone.Name;
string Alerts = cities.DataSets[2];

DataTable dt = new DataTable();
dt.Columns.Add("Version", typeof(string));
dt.Columns.Add("Key", typeof(string));
dt.Columns.Add("Type", typeof(string));
dt.Columns.Add("City", typeof(string));
dt.Columns.Add("Region", typeof(string));
dt.Columns.Add("Country", typeof(string));
dt.Columns.Add("TimeZone", typeof(string));
dt.Columns.Add("Alerts", typeof(string));

DataRow row;
row = dt.NewRow();
row["Version"] = Version;
row["Key"] = Key;
row["Type"] = Type;
row["City"] = City;
row["Region"] = Region;
row["Country"] = Country;
row["TimeZone"] = TimeZone;
row["Alerts"] = Alerts;
dt.Rows.Add(row);

GridView1.DataSource = dt;
GridView1.DataBind();

After running ASP.NET website, the following image is the result of JSON deserialization process.

In this article, System.Text.Json library was introduced, we saw how to install it and use it in an ASP.NET website. Also we discussed the steps to deserialize JSON string in an ASP.NET GridView. In conclusion, this was a demonstration of the concept of JSON deserialization and how System.Text.Json library helps achieve this process.

HostForLIFE.eu ASP.NET Core 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.


 



European ASP.NET Core Hosting :: How To Add JWT Bearer Token Authorization Functionality In Swagger?

clock December 1, 2021 07:18 by author Peter

Swagger (Open API) is a language-agnostic specification for describing and documenting the REST API. Swagger Allows both the Machine and Developer to understand the working and capabilities of the Machine without direct access to the source code of the project. The main objectives of swagger (Open API) are to:

    Minimize the workload to connect with Microservice.
    Reduce the Time Needed to accurately document the Microservice.

Default Addition of Swagger in .NET 5 & .NET 6
Swagger open API is used for developing APIs using ASP.Net Core versions .Net 5 and .Net 6. We can test our all-API Endpoints in a default functionality because it's directly integrated with our API for testing like.

Swagger revealed all our endpoints in the Default view, and we can test them using JSON Schema. Like

However, we have a challenge in that we wish to retrieve data from a secured endpoint that requires a Token as well as a Role-based Token. After submitting a JWT Token and a Role, the endpoint shown below will return data.

[HttpGet]
[Authorize(Roles = "Admin")]
public IEnumerable < WeatherForecast > Get() {
    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast {
        Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
    }).ToArray();
}

Demo
We'll test the endpoint listed below without a token or a role.

After hitting the endpoint, we have the output like


Unauthorized Access because the endpoint requires a JWT Token and a Role in order to access data from the database. By default, Swagger does not provide capability for token-based authorization of endpoints. We are currently adding JWT Token-based functionality to our API.

Default View


Adding JWT Token Functionality in Our API
First and foremost, you must change the default swagger functionality in our startup.cs class

public void ConfigureServices(IServiceCollection services) {
    services.AddDbContext < ApplicationDbContext > (options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
    services.AddControllers();
    services.AddControllers();
    //Default Functionality Added by Swagger
    services.AddSwaggerGen();
    // For Entity Framework
    // For Identity
    services.AddIdentity < ApplicationUser, IdentityRole > ().AddEntityFrameworkStores < ApplicationDbContext > ().AddDefaultTokenProviders();
    // Adding Authentication
    services.AddAuthentication(options => {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        // Adding Jwt Bearer
        .AddJwtBearer(options => {
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new TokenValidationParameters() {
                ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidAudience = Configuration["JWT:ValidAudience"],
                    ValidIssuer = Configuration["JWT:ValidIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
            };
        });
    //services.AddTransient<PersonService, PersonService>();
}

Modifying the Functionality
Just add given below line and replace the,
services.AddSwaggerGen();

With given below lines,
services.AddSwaggerGen(c => {
    c.SwaggerDoc("v1", new OpenApiInfo {
        Title = "JWTToken_Auth_API", Version = "v1"
    });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() {
        Name = "Authorization",
            Type = SecuritySchemeType.ApiKey,
            Scheme = "Bearer",
            BearerFormat = "JWT",
            In = ParameterLocation.Header,
            Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 1safsfsdfdfd\"",
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement {
        {
            new OpenApiSecurityScheme {
                Reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});


Now we can see the Authorize Option for JWT Token Authorization

Step 1
Get the JWT Token for the user by hitting the Login endpoints:
How To Add JWT Bearer Token Authorization Functionality in Swagger

Step 2
Get the JWT Token using Login EndPoint:
How To Add JWT Bearer Token Authorization Functionality in Swagger


We now have the token, which we will add to our application using the Swagger JWT Token Authorization functionality.


Step 3
Hit the Authorize Button and add JWT Token in your application:


 

Now our all endpoints are authorized,


View after adding JWT Token Authentication in Application,


Now you see that we have the lock sign with all our endpoints so let’s try to access the same endpoint data now.


Now you can see that we have a JWT Token and that we have accessed data from a secured API using this token.


After adding the JWT Function in our Application now you can test all the secured endpoint using JWT Token Authentication

We covered how to enable JWT token capabilities in our application and then how to retrieve data from a secured endpoint in this article.

JWT Token Authentication in Asp.net Web API will be the subject of the next article.

“Happy Coding”

HostForLIFE.eu ASP.NET Core 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

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

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


Month List

Tag cloud

Sign in