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 - HostForLIFE :: A Simple Web API Using.Net 8

clock December 19, 2023 06:38 by author Peter

REST API: What is it?
REpresentational State Transfer is what the acronym REST stands for. It's an architectural design that lays forth a set of guidelines for building Web services. REST recommends generating an object from the data a client requests and responding to the user with the object's values via a client-server conversation. For instance, you can construct an object on the server-side if the user requests a Bangalore taxi reservation at a specific location and time. You have an object over here, and you are transmitting the object's state. As a result, Representational State Transfer, or REST, is its name.

An application can be made more appropriate for the internet by utilizing the reduced bandwidth usage provided by the REST architectural style. It is entirely dependent on the resources and is frequently referred to as the "language of the internet."

REST API Fundamentals

The six REST guiding principles are listed below:

Without a state

The body of the request contains the current status of the resource, and the URL is used to identify the resource specifically. The client receives a response from the server via headers, body, or status once the request has been processed. All the necessary information is included in the requests that clients send to servers so that the servers can comprehend the requests. This may appear in the body, headers, query-string arguments, or even the URL. The server API does not cache any state, thus each request is independent of the others. Additionally helpful in scaling the API service in a cloud context is its RESTful characteristic.

Client-Server
The client-server architecture enables a uniform interface and separates clients from the servers. This enhances the portability across multiple platforms as well as the scalability of the server components.

Uniform Interface
To obtain the uniformity throughout the application, REST has the following four interface constraints:

  • Resource identification
  • Resource Manipulation using representations
  • Self-descriptive messages
  • Hypermedia as the engine of application state

Cacheable
To provide a better performance, the applications are often made cacheable. This is done by labeling the response from the server as cacheable or non-cacheable either implicitly or explicitly. If the response is denied as cacheable, then the client cache can reuse the response data for equivalent responses in the future.
Minimal APIs in .Net 8 or .Net 7

Minimal APIs are architected to create HTTP APIs with minimal dependencies. They are ideal for microservices and apps that want to include only the minimum files, features, and dependencies in ASP.NET Core.

Limitations of Minimal API

  • No support for filters: For example, no support for IAsyncAuthorizationFilter, IAsyncActionFilter, IAsyncExceptionFilter, IAsyncResultFilter, and IAsyncResourceFilter.
  • No support for model binding, i.e. IModelBinderProvider, IModelBinder. Support can be added with a custom binding shim.
  • No support for binding from forms. This includes binding IFormFile. We plan to add support for IFormFile in the future.
  • No built-in support for validation, i.e. IModelValidator
  • No support for application parts or the application model. There's no way to apply or build your own conventions.
  • No built-in view rendering support. We recommend using Razor Pages for rendering views.
  • No support for JsonPatch
  • No support for OData
  • No support for ApiVersioning. See this issue for more details.

With the following APIs,

REST APIs follow standard HTTP Verbs like GET, POST, PUT, DELETE, PATCH which are basically CRUD operation on an object. The APIs are arranged to form an internet resource. For example in the above example, we have resource as “todoitem” which can be created, modified, deleted using APIs, and URL format is formed accordingly.

using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext < TodoDb > (opt => opt.UseInMemoryDatabase("TodoList"));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.MapGet("/", () => "Hello World!");
app.MapGet("/todoitems", async (TodoDb db) => await db.Todos.ToListAsync());
app.MapGet("/todoitems/complete", async (TodoDb db) => await db.Todos.Where(t => t.IsComplete).ToListAsync());
app.MapGet("/todoitems/{id}", async (int id, TodoDb db) => await db.Todos.FindAsync(id)
    is Todo todo ? Results.Ok(todo) : Results.NotFound());
app.MapPost("/todoitems", async (Todo todo, TodoDb db) => {
    db.Todos.Add(todo);
    await db.SaveChangesAsync();
    return Results.Created($ "/todoitems/{todo.Id}", todo);
});
app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) => {
    var todo = await db.Todos.FindAsync(id);
    if (todo is null) return Results.NotFound();
    todo.Name = inputTodo.Name;
    todo.IsComplete = inputTodo.IsComplete;
    await db.SaveChangesAsync();
    return Results.NoContent();
});
app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) => {
    if (await db.Todos.FindAsync(id) is Todo todo) {
        db.Todos.Remove(todo);
        await db.SaveChangesAsync();
        return Results.Ok(todo);
    }
    return Results.NotFound();
});
app.Run();
class Todo {
    public int Id {
        get;
        set;
    }
    public string ? Name {
        get;
        set;
    }
    public bool IsComplete {
        get;
        set;
    }
}
class TodoDb: DbContext {
    public TodoDb(DbContextOptions < TodoDb > options): base(options) {}
    public DbSet < Todo > Todos => Set < Todo > ();
}

In summary
The REST architecture style offers a common method for clients to access and retrieve server data as well as a standard approach to arrange resources across the internet. Minimal APIs need to have the least amount of code possible and can be quickly and simply created without the need for authentication or with very little dependencies by sitting behind a gateway that does.

HostForLIFE 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 - HostForLIFE :: Using Serilog for Brilliant Logging in.NET Core

clock December 6, 2023 08:16 by author Peter

Logging: What Is It?
The technique of recording events in real time and adding details like execution time and infrastructure information is known as logging in software. It is essential to every software program, especially when debugging problems. Logs are useful for deciphering errors, locating performance snags, and assisting in issue solving.

Logs are commonly kept in files, databases, or consoles according to the convenience and severity of the application. Although logs can contain a variety of data, error and informational messages are frequently recorded. Informational messages record routine activities such as method calls, user logins, or product checkouts, whereas error messages offer detailed information for troubleshooting.

By offering a generic logging interface that is uniform throughout the framework and external libraries, ASP.NET Core streamlines logging. Problem diagnosis and log navigation are made easier by this standardization. Users can set log verbosity and route logs to various locations, including files, consoles, and databases, using the framework.

Logs are stored by logging providers in ASP.NET Core, and users can set up several providers for their apps. Logging providers like Console, Debug, EventSource, and EventLog (unique to Windows) are part of the standard ASP.NET Core configuration.

Recognizing the Difference: Software System Logging vs. Monitoring

ASP.NET Core has helpful tools for logging—a process of recording events in your applications. System events, user actions, performance indicators, and other events and processes are all recorded in detail through logging. This data, which is commonly kept in a database or log file, enables you to see problems and resolve them, enhance performance, and comprehend how your program is utilized.

Contrarily, monitoring entails keeping an eye on and gauging the performance of your application in real time. When specific criteria are met, such as when the program takes too long to react or experiences an error, it can send warnings or notifications. Monitoring offers important insights for performance optimization and assists in identifying and resolving issues before they affect users.

There are well-known tools in ASP.NET Core, such as Microsoft.Extensions.Helping with logging include Serilog, NLog, and logging. These tools assist you in maintaining a robust and effective software system by making it simpler to handle and analyze the data that your application generates.

Additional Information
Logging in.NET Core allows you to monitor activity within your application. It aids in behavior monitoring, problem solving, and performance analysis. Logging is made organized and efficient with the help of the ILogger API. You can store logs in several locations using different logging providers; built-in and third-party choices are available.

Let's now discuss the distinctions between tracing and logging. The goal of logging is to capture important events in your program and produce a sort of summary. However, tracing goes beyond by providing you with an in-depth overview of all the actions taking place within your application, providing a comprehensive history of its operations.

The six main logging levels in .NET

  • Critical: This is for really serious issues that could make your app stop working, like running out of memory or space on the disk.
  • Error: Use this when something goes wrong, like a database error preventing data from being saved. The app can still work for other things despite encountering errors.
  • Warning: Not as severe as errors, but it indicates a potential problem that might lead to more serious errors. It's a heads-up for administrators.
  • Information: Gives details about what's happening in the app. Helpful for understanding the steps leading to an error.
  • Debug: Useful during development for tracking detailed information. It's not typically used in a live/production environment.
  • Trace: Similar to Debug but may include sensitive info. Rarely used and not utilized by framework libraries.

Implement the External Logging Source to Logging Information of API  and Windows Service - Serilog

Packages need: Serilog.AspNetCore

  • Dot Net CLI - dotnet add package Serilog.AspNetCore --version 8.0.0
  • Package Manager - Install-Package Serilog.AspNetCore -Version 8.0.0

Confiuration of Serilog in API
Settings File

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [ "Serilog.Sinks.File" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "C:/Log001/log_.log",
          "rollOnFileSizeLimit": true,
          "rollingInterval": "Day"
        }
      }
    ]
  }
}

Application Startup updates for Logging
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

/// Step 1
builder.Host.UseSerilog((context, configuration) =>
{
    configuration.ReadFrom.Configuration(context.Configuration);
}
);

var app = builder.Build();


/// Step 2
app.UseSerilogRequestLogging();

app.Run();


Using the setup to Log actions.
In this setup, we employ the "Assembly - Microsoft.Extensions.Logging.Abstractions, Version=8.0.0.0" for logging actions, and we utilize Serilog to write these logs into files. The ILogger interface is injected into the constructor to facilitate logging functionality.
private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    _logger = logger;
}


[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
    _logger.LogInformation("Method Entered");

    var list = Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();

    string message = $"WeatherForecast Count {list.Length}";

    _logger.LogInformation(message);

    _logger.LogInformation("Method Exit");
    return list;
}


Now, to test the logging functionality, run the application and inspect the specified path. Refer to the image below for guidance.

Application Startup updates for Logging
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

/// Step 1
builder.Host.UseSerilog((context, configuration) =>
{
    configuration.ReadFrom.Configuration(context.Configuration);
}
);

var app = builder.Build();


/// Step 2
app.UseSerilogRequestLogging();

app.Run();


Using the setup to Log actions.

In this setup, we employ the "Assembly - Microsoft.Extensions.Logging.Abstractions, Version=8.0.0.0" for logging actions, and we utilize Serilog to write these logs into files. The ILogger interface is injected into the constructor to facilitate logging functionality.
private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    _logger = logger;
}

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
    _logger.LogInformation("Method Entered");

    var list = Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();

    string message = $"WeatherForecast Count {list.Length}";

    _logger.LogInformation(message);

    _logger.LogInformation("Method Exit");
    return list;
}

Now, to test the logging functionality, run the application and inspect the specified path. Refer to the image below for guidance.

HostForLIFE 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