The provided code sets up an ASP.NET Core application using the minimal APIs introduced in .NET 6. Let's break it down into smaller sections and provide comments for clarity
using
Microsoft.AspNetCore.Authentication.JwtBearer;
using
Microsoft.AspNetCore.Authorization;
using
Microsoft.AspNetCore.Server.Kestrel.Core;
using
Microsoft.Extensions.FileProviders;
using
Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using NPOI.SS.Formula.Functions;
using System.Collections.Generic;
using
System.Security.Cryptography.X509Certificates;
// Create builder
var builder =
WebApplication.CreateBuilder(args);
// Configure CORS
builder.Services.AddCors();
// Configure JWT authentication
builder.Services.AddJWTTokenServices(builder.Configuration);
// Configure controllers and API endpoints
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
// Dependency injection for services
builder.Services.AddScoped<IUser, User>();
// Add HttpContextAccessor for accessing HttpContext
builder.Services.AddHttpContextAccessor();
// Add AutoMapper
builder.Services.AddAutoMapper(typeof(Program));
// Configure Kestrel server options
builder.Services.Configure<KestrelServerOptions>(options
=>
{
options.Limits.MaxRequestBodySize = int.MaxValue;
});
// Configure distributed memory cache
builder.Services.AddDistributedMemoryCache();
// Configure session management
builder.Services.AddSession(options =>
{
options.IdleTimeout =
TimeSpan.FromMinutes(5000);
});
// Configure Swagger documentation
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type =
SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT",
In =
ParameterLocation.Header,
Description = "Invalid token response, enter a valid token
response."
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type =
ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
// Build the application
var app = builder.Build();
// Configure CORS policy
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.WithMethods("GET", "POST", "PUT", "DELETE",
"OPTIONS", "HEAD", "*");
});
// Use authentication
app.UseAuthentication();
// Use Swagger
app.UseSwagger();
// Configure Swagger UI
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
});
// Use HTTPS redirection
app.UseHttpsRedirection();
// Serve static files
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new
PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Images")),
RequestPath = new PathString("/wwwroot/Images")
});
// Routing
app.UseRouting();
// Use session
app.UseSession();
// Developer exception page
app.UseDeveloperExceptionPage();
// More HTTPS redirection
app.UseHttpsRedirection();
// Authorization
app.UseAuthorization();
// Map controllers
app.MapControllers();
// Map default controller route
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
// Run the application
app.Run();
-------------------------------
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public static async Task<MessageModel>
SendSms(string message, string mobileNumber)
{
// Initialize the model
MessageModel model = new MessageModel();
try
{
// Create the payload
var payload = new
{
Message =
message,
MobileNumber =
mobileNumber
};
// Create HttpClient instance
using (var client = new HttpClient())
{
// Set base address - replace "Sms" with the actual base
URL
client.BaseAddress = new Uri("Sms");
// Send POST request
var postTask = await client.PostAsync("", new
StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"));
// Ensure successful response
postTask.EnsureSuccessStatusCode();
// Read response content
var jsonResponse = await
postTask.Content.ReadAsStringAsync();
// Deserialize response to MessageModel
model =
JsonConvert.DeserializeObject<MessageModel>(jsonResponse);
}
}
catch (HttpRequestException ex)
{
// Handle HTTP request exceptions
model.Message =
ex.Message;
model.Status = "Failed";
}
catch (JsonException ex)
{
// Handle JSON serialization/deserialization exceptions
model.Message =
ex.Message;
model.Status = "Failed";
}
catch (Exception ex)
{
// Handle other exceptions
model.Message =
ex.Message;
model.Status = "Failed";
}
return model;
}
// Define MessageModel class
public class MessageModel
{
public string Message { get; set; }
public string Status { get; set; }
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace PaginationExample
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class PageSizer
{
public PageSizer(
int totalItems,
int currentPageSize = 1,
int pageSize = 10,
int maxPageSizes = 10)
{
// calculate total PageSizes
var totalPageSizes = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
// ensure current PageSize isn't out of range
if (currentPageSize < 1)
{
currentPageSize = 1;
}
else if (currentPageSize >
totalPageSizes)
{
currentPageSize = totalPageSizes;
}
int startPageSize, endPageSize;
if (totalPageSizes <=
maxPageSizes)
{
// total PageSizes less than max so show all PageSizes
startPageSize = 1;
endPageSize =
totalPageSizes;
}
else
{
// total PageSizes more than max so calculate start and end
PageSizes
var
maxPageSizesBeforeCurrentPageSize = (int)Math.Floor((decimal)maxPageSizes / (decimal)2);
var
maxPageSizesAfterCurrentPageSize = (int)Math.Ceiling((decimal)maxPageSizes / (decimal)2) - 1;
if (currentPageSize <=
maxPageSizesBeforeCurrentPageSize)
{
// current PageSize near the start
startPageSize = 1;
endPageSize = maxPageSizes;
}
else if (currentPageSize +
maxPageSizesAfterCurrentPageSize >= totalPageSizes)
{
// current PageSize near the end
startPageSize = totalPageSizes - maxPageSizes + 1;
endPageSize = totalPageSizes;
}
else
{
// current PageSize somewhere in the middle
startPageSize = currentPageSize - maxPageSizesBeforeCurrentPageSize;
endPageSize = currentPageSize + maxPageSizesAfterCurrentPageSize;
}
}
// calculate start and end item indexes
var startIndex =
(currentPageSize - 1) * pageSize;
var endIndex =
Math.Min(startIndex + pageSize - 1, totalItems - 1);
// create an array of PageSizes that can be looped over
var PageSizes = Enumerable.Range(startPageSize, (endPageSize + 1) -
startPageSize);
// update object instance with all PageSizer properties required
by the view
TotalItems =
totalItems;
CurrentPageSize
= currentPageSize;
PageSize =
pageSize;
TotalPageSizes =
totalPageSizes;
StartPageSize =
startPageSize;
EndPageSize =
endPageSize;
StartIndex =
startIndex;
EndIndex =
endIndex;
PageSizes =
PageSizes;
}
public int TotalItems { get; private set; }
public int CurrentPageSize { get; private set; }
public int PageSize { get; private set; }
public int TotalPageSizes { get; private set; }
public int StartPageSize { get; private set; }
public int EndPageSize { get; private set; }
public int StartIndex { get; private set; }
public int EndIndex { get; private set; }
public IEnumerable<int> PageSizes { get; private set; }
}
class Program
{
static void Main(string[] args)
{
// Get sample users
var users = GetUsers();
// Display first page of users with a page size of 10
DisplayPaginatedUsers(users, 1, 10);
// Prompt user to navigate through pages
bool exit = false;
while (!exit)
{
Console.WriteLine("\nPress 'n' for next
page, 'p' for previous page, or 'q' to quit:");
var key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.N:
Console.Clear();
DisplayPaginatedUsers(users, Math.Min(pageSizer.CurrentPageSize + 1,
pageSizer.TotalPageSizes), 10);
break;
case ConsoleKey.P:
Console.Clear();
DisplayPaginatedUsers(users, Math.Max(pageSizer.CurrentPageSize - 1, 1),
10);
break;
case ConsoleKey.Q:
exit
= true;
break;
default:
Console.WriteLine("Invalid input. Please
try again.");
break;
}
}
}
public static List<User> GetUsers()
{
// Simulate fetching users from a data source
return Enumerable.Range(1,
100) //
Generating 100 sample users
.Select(i => new User { Id = i, Name = $"User
{i}" })
.ToList();
}
public static void
DisplayPaginatedUsers(List<User> users, int currentPage, int pageSize)
{
// Calculate pagination information
var pageSizer = new PageSizer(users.Count,
currentPage, pageSize);
// Display pagination details
Console.WriteLine($"Page {pageSizer.CurrentPageSize}
of {pageSizer.TotalPageSizes}, " +
$"Total Items: {pageSizer.TotalItems}");
// Display current page of users
foreach (var user in
users.Skip(pageSizer.StartIndex).Take(pageSizer.PageSize))
{
Console.WriteLine($"ID: {user.Id}, Name: {user.Name}");
}
}
}
}