Write a program in ASP.NET Core to get all the properties of IHttpRequestFeature which are of string type.
The HttpContext API that applications and middleware use to process requests has an abstraction layer underneath it called feature interfaces. Each feature interface provides a granular subset of the functionality exposed by HttpContext. These interfaces can be added, modified, wrapped, replaced, or even removed by the server or middleware as the request is processed without having to re-implement the entire HttpContext. They can also be used to mock functionality when testing.
IHttpRequestFeature: Defines the structure of an HTTP request, including the protocol, path, query string, headers, and body. This feature is required in order to process requests.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Hosting;
using System.Reflection;
using System.Text;
namespace WebApplication1
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(ctx =>
{
var requestFeature = ctx.Features.Get<IHttpRequestFeature>();
StringBuilder sb = new StringBuilder();
foreach (PropertyInfo prop in requestFeature.GetType().GetProperties())
{
if (prop.PropertyType == typeof(string))
{
sb.Append(prop.Name + ": " + prop.GetValue(requestFeature) + System.Environment.NewLine);
}
}
foreach (string hk in requestFeature.Headers.Keys)
{
sb.Append(hk);
sb.Append(": ");
sb.Append(requestFeature.Headers[hk]);
sb.Append(System.Environment.NewLine);
}
return ctx.Response.WriteAsync(sb.ToString());
});
}
}
}
Give examples of different types of Features available for HttpContext.
app.Run(ctx =>
{
var maxsize = ctx.Features.Get()?.MaxRequestBodySize;
var serverAddress = ctx.Features.Get().Addresses.FirstOrDefault();
var c = ctx.Features.Get().RequestCulture.UICulture.DateTimeFormat;
var sessionId = ctx.Features.Get().Session.Id;
var sessionKeys = ctx.Features.Get().Session.Keys;
var responseFeature = ctx.Features.Get().StatusCode;
}
Can we send body in get request?
What is request body
When you need to send data from a client (let's say, a browser) to your API, you send it as a request body. A request body is data sent by the client to your API. A response body is the data your API sends to the client. HTTP Body Data is the data bytes transmitted in an HTTP transaction message immediately following the headers if there is any (in the case of HTTP/0.9 no headers are transmitted). Most HTTP requests are GET requests without bodies
What is the difference between request body and content?
Body is a Stream , and is just a chunk of data representing the body of the request. Content is a HttpContent . Content can have extra information like headers to describe the Body. You can read the data (of the body) from the Content as a Stream (as you have shown).
What is HTTP payload?
The payload of an API is the data you are interested in transporting to the server when you make an API request. Simply put, it is the body of your HTTP request and response message.
Which HTTP methods have a body?
HTTP request bodies are theoretically allowed for all methods except TRACE, however they are not commonly used except in PUT, POST and PATCH.
What is header and payload?
In information technology, header refers to supplemental data placed at the beginning of a block of data being stored or transmitted. In data transmission, the data following the header is sometimes called the payload or body.
What are the 4 types of HTTP request methods?
Different kinds of HTTP requests - GeeksforGeeks
HTTP (Hypertext Transfer Protocol) specifies a collection of request methods to specify what action is to be performed on a particular resource. The most commonly used HTTP request methods are GET, POST, PUT, PATCH, and DELETE. These are equivalent to the CRUD operations (create, read, update, and delete).
What is API and payload?
What Is A Payload In API? The payload within an API is the data transporting to the server at the point in time when a user makes an API request. This is the body of the HTTP request, as well as the response message. Additionally, this API can be sent or received through various formats, such as JSON or XML.
What is JSON Payload? The request payload is important information in a data block that clients send to the server in the body of an HTTP POST, PUT or PATCH message that contains important information about the request. The Payload can be sent or received in various formats, including JSON.
What is rest calls?
REST API Tutorial – REST Client, REST Service, and API Calls ...
REST is basically a set of rules for communication between a client and server. There are a few constraints on the definition of REST: Client-Server Architecture: the user interface of the website/app should be separated from the data request/storage, so each part can be scaled individually.22-A
What is PATCH in REST API?
The PATCH HTTP method is used to modify the values of the resource properties. The PATCH HTTP method requires a request body. The body of the request must contain representation of the JSON Patch operations that you want to perform on the resource.
What is the maximum IP payload?
The maximum payload size for IP packets is limited by the Total Length field in the IP packet header; that field is 16 bits long, meaning the maximum possible value is 216 and the highest possible value for packet length is 65,535 -- no payload can be larger, minus the number of bytes required for the packet header.
What is difference between put and POST?
Use PUT when you want to modify a single resource that is already a part of the resources collection. PUT overwrites the resource in its entirety. Use PATCH if the request updates part of the resource. Use POST when you want to add a child resource under resources collection.
What is an API endpoint?
In summary, an API endpoint is a specific location within an API that accepts requests and sends back responses. It's a way for different systems and applications to communicate with each other, by sending and receiving information and instructions via the endpoint.
What is REST and soap?
Representational state transfer (REST) is a set of architectural principles. Simple object access protocol (SOAP) is an official protocol maintained by the World Wide Web Consortium (W3C).
What is dump and load in JSON?
loads() takes in a string and returns a json object. json. dumps() takes in a json object and returns a string.
How to generate single blank space in C#
How to generate read only array in C#
How to repeat a character in C#
string rept = new string('w', 3); will be www
OR,
public static string RepeatChar(char text, int n)
{
StringBuilder stringBuilder = new StringBuilder();
return stringBuilder.Append(text, n).ToString();
}
How to repeat a word in C#
public static class Helper
{
internal static string RepeatText(string text, int n, string separator)
{
string[] data = new string[n];
for (int i = 0; i < n; i++)
{
data[i] = text;
}
return string.Join(separator, data);
}
}
//call the method in client class
Console.WriteLine(Helper.RepeatText("Test", 10,"-"));
OR
public static string RepeatText(string text, int n, string separator)
{
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < n; i++)
{
stringBuilder.Append(text);
if (i < n - 1)
{
stringBuilder.Append(separator);
}
}
return stringBuilder.ToString();
}
//call the method in client class
Console.WriteLine(Helper.RepeatText("Test", 10,"-"));
Create an extension method of string.
public static string RepeatText(this string text, uint n)
{
return string.Concat(System.Linq.Enumerable.Repeat(text, (int)n));
}
How to convert a string into array in C#
string sentence = "Life is such a cruel drAMA which cannot be understood by anyone";
string[] words = sentence.Split( ' ', StringSplitOptions.RemoveEmptyEntries);
- StringSplitOptions.RemoveEmptyEntries ignores extra spaces in string so that array will not have empty zls elements.
- StringSplitOptions.TrimEntries specifies that whitespace should be trimmed from each substring in the result.
How to concatenate strings in C#.
- Using + operator
- string name = firstName + " " + lastName;
- String Interpolation
- string bookAuthor = $"{author} is the author of {book}.";
- String.Concat() method
- string arrayStr = string.Concat(arraydata);
- String.Join() method
- string data = string.Join(separator, array);
- String.Format() method
- string date = String.Format("Today's date is {0}", DateTime.Now);
- StringBuilder.Append() method
static void Main(string[] args)
{
string sentence = "Life is such a cruel drAMA which cannot be understood by anyone";
string[] words = sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
Console.WriteLine(sb.AppendJoin("~", words).ToString());
Console.ReadLine();
}
Extract all numbers from string in C#
static void Main(string[] args)
{
string sentence = "Life is 1, 2, 3 4 and go to 1000000 such a cruel drAMA";
// Match: single first match
var result = System.Text.RegularExpressions.Regex.Match(sentence, @"\d+").Value;
Console.WriteLine(result);
// MatchCollection: all matches
var results = System.Text.RegularExpressions.Regex.Matches(sentence, @"\d+");
foreach (var item in results)
{
Console.WriteLine( item);
}
Console.WriteLine(results);
Console.ReadLine();
}
Use LINQ to Extract all numbers from string in C#
string sentence = "Life is 1, 2, 3 4 and go to 1000000 such a cruel drAMA";
string s = new String(sentence.Where(char.IsDigit).ToArray());
Console.WriteLine(s);
Nice solution for integers! Be aware that this won't work if you're trying to parse a decimal number because the decimal point is not a digit.
How to pass dynamic/variable size array as parameter in a method in C#
Use the params keyword before the normal array parameter in the method.
public void Show(params int[] val) // Params Paramater
{ }
EXAMPLE
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
The first argument of predicate represents the element to test. The second argument represents the zero-based index of the element within source.
Overloads
Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)
Filters a sequence of values based on a predicate.
Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Int32,Boolean>>)
Filters a sequence of values based on a predicate. Each element's index is used in the logic of the predicate function.
get all odd index chars in a string in C#
string sentence = "Lifesucha cruel drAMA";
// get all odd index chars using LINQ char.IsDigit(char, index)
char[] s = sentence.Where((c, i) => i % 2 == 0).ToArray();
// join the odd index chars
string result = string.Join("~", s);
Console.WriteLine(result);
IEnumerable Vs IQueryable In LINQ
IEnumerable
- IEnumerable exists in the System.Collections namespace.
- IEnumerable is suitable for querying data from in-memory collections like List, Array and so on.
- While querying data from the database, IEnumerable executes "select query" on the server-side, loads data in-memory on the client-side and then filters the data.
- IEnumerable is beneficial for LINQ to Object and LINQ to XML queries.
IQueryable
- IQueryable exists in the System.Linq Namespace.
- IQueryable is suitable for querying data from out-memory (like remote database, service) collections.
- While querying data from a database, IQueryable executes a "select query" on server-side with all filters.
- IQueryable is beneficial for LINQ to SQL queries.
NOTE The syntax is same, difference is internal.
Higher-order function: a function that either returns a function or accepts functions as arguments.
Difference between TryParse and Parse?
string data = "10";
string data2 = "10s";
int number = int.Parse(data); // returns 1o
Console.WriteLine(number);
int number2 = int.Parse(data2); // throws System.FormatException exception
Console.WriteLine(number2);
// TryParse
string data = "10";
int number;
bool success = int.TryParse(data, out number);
var x = success ? data + " is a number." : "Failed";
Console.WriteLine(x);
// replace text in a string
string quote = "Life is like riding a bicycle. To keep your balance, you must keep moving";
quote = quote.Replace("keep", "deep");
System.Text.RegularExpressions.Regex.Replace
// Use Regex.Replace for more flexibility.
// Replace "the" or "The" with "many" or "Many".
// using System.Text.RegularExpressions
string replaceWith = "many ";
source = System.Text.RegularExpressions.Regex.Replace(source, "the\\s", LocalReplaceMatchCase,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
Console.WriteLine(source);
C# dynamic array
C# supports both static and dynamic arrays. If you're new to arrays, check out Arrays in C# (Download Sample Project).
A static array has a fixed size and is defined when an array is declared. The following code defines an array that can hold 5 int type data only.
int[] odds = new int[5];
C#
Arrays in C# are the 0th index. That means the first item of an array starts at the 0th position. The position of the last item on an array will be a total number of items - 1. So, if an array has five items, the last item of the array is accessed using index 4.
The following code adds five items to the array.
odds[0] = 1;
odds[1] = 3;
odds[2] = 5;
odds[3] = 7;
odds[4] = 9;
C#
In a fixed array, if you try to add more items than its range, you will get the following error:
odds[5] = 11;
C#
Unhandled exception. System.IndexOutOfRangeException: The index was outside the bounds of the array.
at Program.Main(String[] args) in C:\Mahesh\DotNetCore\ArraysFAQ\ArraysFAQ\Program.cs:line 14
A dynamic array does not have a predefined size. The size of an active array increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined. The following code snippet declares a dynamic array where the size of the array is not provided.
int[] numArray = new int[] {};
C#
Dynamic arrays can be initialized as static arrays. The following code snippet declares a dynamic array and initializes.
int[] numArray = new int[] { 1, 3, 5, 7, 9, 11, 13 };
C#
The following code sample declares three dynamic arrays of different data types.
// Dynamic array of int type
int[] numArray = new int[] {1, 3, 5, 7, 9, 11 };
// Dynamic array of string type
string[] strArray = new string[] { "Mahesh Chand",
"David McCarter", "Allen O'neill", "Chris Love" };
// Dynamic array of a collection
List<string> authors = new List<string>();
authors.Add("Mahesh Chand");
authors.Add("David McCarter");
authors.Add("Allen O'neill");
authors.Add("Chris Love");
C#
Access C# dynamic arrays
We can access both dynamic arrays and static arrays the same way by passing the item index in the array.
// Dynamic array of int type
int[] numArray = new int[] {1, 3, 5, 7, 9, 11 };
Console.WriteLine(numArray[0]);
Console.WriteLine(numArray[1]);
Console.WriteLine(numArray[2]);
Console.WriteLine(numArray[3]);
Console.WriteLine(numArray[4]);
Console.WriteLine(numArray[5]);
C#
A foreach loop can be used to iterate through the elements of an array.
// Dynamic array of string type
string[] strArray = new string[] { "Mahesh Chand",
"David McCarter", "Allen O'neill", "Chris Love" };
foreach (string str in strArray)
Console.WriteLine(str);
C#
When to use dynamic arrays
Unless you limit an array size, the default arrays are dynamic arrays. Dynamic arrays are used when you’re unsure about the number of elements an array can store. Static arrays should be used when you do not want an array to hold more items than it is predefined size.
Register IHttpClientFactory by calling AddHttpClient in Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddHttpClient();
An IHttpClientFactory can be requested using dependency injection (DI). The following code uses IHttpClientFactory to create an HttpClient instance:
public class BasicModel : PageModel
{
private readonly IHttpClientFactory _httpClientFactory;
public BasicModel(IHttpClientFactory httpClientFactory) =>
_httpClientFactory = httpClientFactory;
public IEnumerable<GitHubBranch>? GitHubBranches { get; set; }
public async Task OnGet()
{
var httpRequestMessage = new HttpRequestMessage(
HttpMethod.Get,
"https://api.github.com/repos/dotnet/AspNetCore.Docs/branches")
{
Headers =
{
{ HeaderNames.Accept, "application/vnd.github.v3+json" },
{ HeaderNames.UserAgent, "HttpRequestsSample" }
}
};
var httpClient = _httpClientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
if (httpResponseMessage.IsSuccessStatusCode)
{
using var contentStream =
await httpResponseMessage.Content.ReadAsStreamAsync();
GitHubBranches = await JsonSerializer.DeserializeAsync
<IEnumerable<GitHubBranch>>(contentStream);
}
}
}
Different approaches to send data from form in ASP.NET Core
- Request.Form["form-control-name"] in action method body.
- Parameter binding: The form name parameter binding with action method parameter.
- FromFormAttribute as action parameter.
- BindPropertyAttribute: The form name parameter binding with a property of controller class.
- BindPropertiesAttribute The form name parameters binding with different properties of controller class.
- IFormCollection as action parameter.
- Model: Create a model and pass it parameter to the action method.
- TryUpdateModelAsync: In this case, we use create a model and pass it as parameter to UpdateModel (model) method. The UpdateModel method is called in the action method body.
Q. Create a partial view for Menu and add it in the layout view. Also add logo image in the Menu.
Q. Why logo image is not working in my menu partial view?
Ans. You may be missing UseStaticFiles() middleware in Configure method.
Q. Why partial tag is not working in my layout view?
Ans. You may be missing addTagHelper in _ViewImports.cshtml file.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Q. In which view @RenderBody is used?
Layout view
Q. How can you add a layout view without scaffolding?
Use Layout property in a view to add a layout view without scaffolding. Use full path of the layout view with its extension as given below.
How to access Configuration during startup in ASP.NET Core 6?
WebApplicationBuilder returned by WebApplication.CreateBuilder(args) exposes Configuration and Environment properties:
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration; // allows both to access and to set up the config
IWebHostEnvironment environment = builder.Environment;
Once we have the builder created, the configuration is available.
Let's assume you have the default appsettings.json in place. The example code below would return the configuration Default log level setting from the JSON configuration file.
builder.Configuration["Logging:LogLevel:Default"] // returns "Warning"
Once the app is running, you can access the Configuration settings via dependency injection in other classes of your application.
public MyClass(IConfiguration configuration)
{
var logLevel = configuration["Logging:LogLevel:Default"];
}
NOTE: A nice feature worth considering it to create a class that represents your settings and then bind the configuration to an instance of that class type. For example, let's assume you create a new class called MyAppSettings with the same structure as your appsettings.json, you can do the following:
var myAppSettings = builder.Configuration.Get();
string logLevel = myAppSettings.Logging.LogLevel.Default;
How to get project level configuration object
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Configuration.AddJsonFile($"appsettings.Dev.json", optional: true);
builder.Configuration.AddEnvironmentVariables();
// projectwide instances
public IConfiguration _configuration;
public AccountsAPIController(IConfiguration configuration)
{
_configuration = configuration;
}
// _configuration.GetConnectionString("DefaultConnection");
Note that the namespace for IConfiguration is Microsoft.Extensions.Configuration.
How to refactor code in Program.cs in ASP.NET Core?
using AutoMapper;
using MicroKnights.Log4NetHelper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
...
//all your using directives
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
//a variable to hold configuration
IConfiguration Configuration;
var builder = WebApplication.CreateBuilder(args);
Configuration = builder.Configuration;
// call some methods
ConfigureAuth(builder.Services); // builder.Services returns object of IServiceCollection which belongs to Microsoft.Extensions.DependencyInjection namespace.
ConfigureRedis(builder.Services);
ConfigureSession(builder.Services);
ConfigureMvc(builder.Services);
ConfigureServices(builder.Services);
var app = builder.Build();
ConfigureMiddleWare(app);
app.Run();
// we are done with the main part, now the methods
void ConfigureMvc(IServiceCollection services)
{
builder.Services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
config.Filters.Add(new AuthorizeFilter(policy));
})
.AddRazorPagesOptions(options => { options.Conventions.AddPageRoute("/Home/Login", ""); })
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
}
void ConfigureSession(IServiceCollection services)
{
builder.Services.AddSession(options =>
{
options.Cookie.Name = "mygreatsite_session";
options.IdleTimeout = TimeSpan.FromMinutes(60);
});
}
void ConfigureRedis(IServiceCollection services)
{
var redisConfig = new RedisOptions();
Configuration.GetSection(RedisOptions.RedisConfig).Bind(redisConfig);
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConfig.ConnectionString;
options.InstanceName = "mygreatsite_";
});
services.AddDataProtection()
.SetApplicationName("MyGreatSite.Website")
.PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConfig.ConnectionString), "DataProtection-Keys");
}
void ConfigureMiddleWare(WebApplication app)
{
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseRouting();
app.UseCors("default");
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute().RequireAuthorization();
endpoints.MapControllerRoute(
name: "Default",
pattern: "{controller=Home}/{action=Login}"
);
});
}
What is the default directory for static files in ASP.NET Core?
Static files are stored within the project's web root directory. The default directory is {content root}/wwwroot , but it can be changed with the UseWebRoot method.
How do I redirect in ASP.NET Core?
Various ways of redirecting a request in ASP.NET Core
- Redirect() method
- RedirectPermanent() method
- RedirectPreserveMethod() method
- RedirectPermanentPreserveMethod() method
- RedirectToAction() method
What is the default drive path?
The default directory path for most versions of Windows is c:\Windows (for Windows NT 4 and 2000, it is c:\WinNT).
What is static files in .NET Core?
Static files like JavaScript files, images, CSS files that we have on the file system are the assets that ASP.NET Core application can serve directly to clients. Static files are typically located in the web root (wwwroot) folder.
What is the default route for ASP.NET Core API?
The default route template for Web API is "api/{controller}/{id}". In this template, "api" is a literal path segment, and {controller} and {id} are placeholder variables.
What is the default location of ASP.NET SessionID?
By Default Session Id is Stored in Client m/c in the form of text file. It is Called Cookie.
What is the difference between return View and RedirectToAction?
The View() method doesn't make new requests, it just renders the view without changing URLs in the browser's address bar. The RedirectToAction() method makes new requests and URL in the browser's address bar is updated with the generated URL by MVC.
What is the default logger in ASP.NET Core?
The default ASP.NET Core configures the following logging providers: Console, Debug, EventSource, and EventLog (on Windows). You can override the default set of logging providers by calling ClearProviders and adding the specific logging providers that you need.
What is the default route of .NET controller?
The default route table contains a single route (named Default). The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id. The Default route maps this URL to the parameters: controller = Home.
What is the default route for swagger?
The default URL for the swagger-ui will be http://localhost:8080/swagger-ui.html.
What is the default request size in ASP.NET Core?
approximately 28.6MB
Which session state mode is default?
In-process mode is the default session state mode and is specified using the InProc SessionStateMode enumeration value. In-process mode stores session state values and variables in memory on the local Web server.
Where is generated SessionID stored?
The session ID can be stored as a cookie, form field, or URL (Uniform Resource Locator). Some Web servers generate session IDs by simply incrementing static numbers.
How to change http to https in ASP.NET Core?
For ASP.NET MVC Web app
In the Configure your new project dialog, enter HTTPS_Project for Project name > Create.
You will see on the right hand side, under Advanced, there is choice: Configure for HTTPS, by default, it is checked.
How to check the URL of a request in C#?
In ASP.NET
string url = HttpContext. ...
string host = HttpContext.Current.Request.Url.Host; ...
string authority = HttpContext.Current.Request.Url.Authority; ...
string port = HttpContext.Current.Request.Url.Port; ...
string absolutepath = HttpContext.Current.Request.Url.AbsolutePath;
In ASP.NET Core
public string Index()
{
// create own url
UriBuilder builder = new UriBuilder();
builder.Scheme = "http";
builder.Host = "localhost";
builder.Port = 5001;
builder.Path = "/test";
Uri uri = builder.Uri;
string madeurl = uri.OriginalString;
// check the request url
string url1 = UriHelper.GetDisplayUrl(HttpContext.Request);
string url2 = HttpContext.Request.GetDisplayUrl();
return madeurl + "\n" + url1 + "\n" + url2 + "\n";
}
Is ViewBag slower than ViewData in MVC?
ViewBag is slower than ViewData.
Why we use TempData in MVC?
TempData is used to transfer data from view to controller, controller to view, or from one action method to another action method of the same or a different controller. TempData stores the data temporarily and automatically removes it after retrieving a value.
What is the difference between RedirectToAction and Redirecttolocal?
RedirectToAction is meant for doing 302 redirects within your application and gives you an easier way to work with your route table. Redirect is meant for doing 302 redirects to everything else, specifically external URLs, but you can still redirect within your application, you just have to construct the URLs yourself.
What is the difference between redirect and forwarding a domain?
A Forward changes URLs on the server without telling the browser, but a Redirect tells the browser to fetch the new URL. But when it comes to DNS, you can think of a Redirect and a Forward as practically the same thing.
How do I reset my session state?
Session State can also be cleared by going to Settings → Clear Cache, followed by Rerunning the app.
What is default session time and path? How to change it ?
Default session time in PHP is 1440 seconds (24 minutes) and the Default session storage path is temporary folder/tmp on server.
What is the difference between TempData keep and peek in MVC?
The Keep() and Peek() method is used to read the data without deletion the current read object. You can use Peek() when you always want to hold/prevent the value for another request. You can use Keep() when prevent/hold the value depends on additional logic. Overloading in TempData.
What is the difference between URL rewrite and URL redirect?
Users can easily type the latter to reach directly at the specific page on the website. URL Rewrite is a server-side request while URL Redirect is a client-side request. This means that the user cannot see the original big and ugly URL with Url Rewriting.
How to disable session state in Web API?
Disable session state at the application level
Start Microsoft Visual Studio . ...
In Solution Explorer, double-click Web. ...
Locate the <sessionState> section, and set the mode value to Off.
Save the file and/or the project to disable session state throughout all pages in the application.
What is the default timeout for HTTP session?
The default timeout value for an inactive user session is 30 minutes. This means that when a user closes their browser without logging out first, their user session and any open host sessions will be cleaned up after 30 minutes. The minimum timeout value allowed is 600 seconds (10 minutes).
Is TempData stored in session?
People who used TempData in ASP.NET MVC, probably knows that by default TempData is stored in a Session state. This means that the web application must have sessions enabled.
Why is session stateless?
Stateful vs Stateless: Full Difference - A stateless protocol is one in which the receiver is not required to keep session state from previous requests. The sender sends relevant session state to the receiver in such a way that each request may be interpreted without reference to prior requests' session state, which the receiver retains.
How do I disable REST API endpoint?
Open the API Gateway console. In the navigation pane, choose APIs, and then choose your REST API. In the navigation pane, choose Settings. For the Default Endpoint, choose Disabled, and then choose Save Changes.
How to refresh page without reloading in MVC?
How can I fetch the new data without refreshing the page? You can use partial view to list the records and use jQuery Ajax to refresh it, and you can also use jQuery Ajax to perform CRUD operations in asp.net core MVC. Then, enable migration and add the Customer table in the database, using the ApplicationDbContext which is child class of DbContext.
How to hide URL parameters in C#?
You can't hide URL parameters. If the reason you want the parameter hidden is so that people can't access ids they are not authorized to, then the solution is to amend your code so that people only access data they are authorized to access.
Is SOAP stateless or stateful?
SOAP is by default stateless, but it is possible to make this API stateful. It is stateful, i.e. no server-side sessions occur. It is data-driven, meaning that data is available as resources. It has WS-security (Enterprise-level security) with SSL support.
Is JWT stateless?
Stateless authentication uses tokens, most often a JSON Web Token (JWT), that contain the user and client information. The server only has to match the token key and cryptographic signature with the information on file, meaning it can do far less work in looking up identity provider (IdP) information.
Is HTTP stateful or stateless?
The HTTP protocol is a stateless one. This means that every HTTP request the server receives is independent and does not relate to requests that came prior to it.
How to call endpoint from REST API?
Calling REST APIs
Add a Datasource with OpenAPI specification. Datasource for REST service without OpenAPI specification.
Add a service. Define the methods that map to the operations.
Add a Controller. Inject the Service in the constructor. Add the REST endpoints.
More examples.
Further reading.
What are the different endpoint types in REST API?
An API endpoint type refers to the hostname of the API. The API endpoint type can be edge-optimized, regional, or private, depending on where the majority of your API traffic originates from.
How to stop page postback in MVC?
The postback on submit button can be avoided by giving return=false in the event handler function as below.
<INPUT type='submit' value='Submit' onclick='return false;'>
What are nullable and non-nullable types?
Nullable types are variables that can hold null .
Non-null types are variables that can't hold null .
How to declare nullable C#?
In C#, we can declare the nullable type as: Nullable<dataType> variableName = null; Here, dataType is Value Data Types like floating point type, integer type, boolean type etc. There is also a short cut to this syntax which involves? operator along with data type as mentioned below:
data_type? variable_name = null;
Advantages of Nullable Type in C#
Nullable type is used in database applications. If a column in a database requires null values, a nullable type can be used to assign null values to the column.
Is nullable a reference type?
Nullable reference types are available in code that has opted in to a nullable aware context. Nullable reference types, the null static analysis warnings, and the null-forgiving operator are optional language features. All are turned off by default.
What is a nullable class in C#?
A type is said to be nullable if it can be assigned a value or can be assigned null , which means the type has no value whatsoever. By default, all reference types, such as String, are nullable, but all value types, such as Int32, are not.
What is the difference between get type and type of?
typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System. Type containing meta-information on a type.
What is the difference between string and nullable string?
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
What is the difference between nullable and C#?
In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a special feature to assign a null value to a variable that is known as the Nullable type. The Nullable type allows you to assign a null value to a variable.
What makes a string null?
A string is null if it has not been assigned a value (in C++ and Visual Basic) or if it has explicitly been assigned a value of null .
How to make a string not nullable in C#?
The only way to create a non-nullable type is to declare a struct - structs, however, cannot inherit or be inherited from. Using properties as you are is most likely the best way, or null-coalescing during deserialization as previously suggested, but C# is simply designed to handle null values.
Why use Nullable types?
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.
How to check if a string exists in a string C#?
Contains() Method. In C#, String. Contains() is a string method. This method is used to check whether the substring occurs within a given string or not.
Why is string nullable in C#?
C# 8.0 nullable references: defeating the point with empty ...
The whole reason C# 8 introduced its Nullable Reference Types feature was to avoid situations in which properties and other variables do not have a usable value.
Is string nullable by default?
The object and string types have a default value of null, representing a null reference that literally is one that does not refer to any object.
What is a non-nullable string?
Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil.
How to check if a string is nullable in C#?
In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.
Introduction to Partial View in MVC
A partial view is a portion of view content.
Partial view can be used on multiple views.
Break up large view into small components(i.e. partial views) with the help of partial view.
Partial view follows DRY principle.
The file extension for partial view depends on two things i.e. view engine and the programming language.
File extension for Razor Partial View in C# is .cshtml.
File extension for Razor Partial View in VB is .vbhtml.
File extension for ASPX Partial View in C# or VB is .ascx.
Partial view cannot have HTML tags like HTML, head, title, body, meta. It will have other HTML tags like h1, p, div etc.
How to Create Partial View in MVC?
A partial view has same file extension(. cshtml) as regular view. To create a partial view do right click on shared folder (\Views\Shared) in solution explorer and click on "Add New View" option and then give the name for partial view and also checked the Create a partial view option as shown in fig.
Rendering Partial View
A partial view is rendered by using the ViewUserControl class that is inherited/derived from the ASP.NET UserControl class. The Partial, RenderPartial, RenderAction helper methods are used to render partial view in mvc3 razor.
<div> @Html.Partial("_Comments") </div>
<div> @{Html.RenderPartial("_Comments");} </div>
The main difference between above two methods is that the Partial helper method renders a partial view into a string while RenderPartial method writes directly into the response stream instead of returning a string.
<div> @{Html.RenderAction("_Category","Home");} </div>
Render Partial View Using jQuery
Sometimes we need to load a partial view within a popup on run time like as login box, then we can use jQuery to make an AJAX request and render a Partial View into the popup. In order to load a partial view within a div we need to do like as:
<script type="text/jscript">
$('#divpopup').load('/Shared/_ProductCategory’);
</script>
How to Create Partial View in MVC?
Step 1: First, we need to create an MVC Project that is from an empty template. Now right-click on the “Controllers” and now select “Add” >> “Controller”.
Step 2: To add an empty controller we need to select “MVC 5 Controller – Empty”. Now add it by clicking on “Add”.
Step 3: Give a proper name to the controller.
Step 4: Now create a view by right clicking on “Index” and selecting the “Add View” option.
Step 5: Now give the proper name to the view and select “Empty (Without model)” as the template. Click on the “Add” button.
Step 6: Right-click on “Views” and select on the “Add” and “New Folder”.
Step 7: Name the Folder as Shared, which will create it under the View.
Step 8: Now right-click on the created Folder “Shared” and select the Add option and the View.
Step 9: Name the view “Layout” and select template as a “Empty (Without Model)”.
Step 10: Now we can design our layout, as we want in “Layout.cshtml”.
We can create content area, header, side bar and footer, as we want for an application in the “Layout.cshtml”.
So we have created a Simple ASP.NET MVC Application using empty template and by adding Home Controller with layout action.
Now we want to print “Welcome To AppliedK” in many of the pages.so we will be creating Partial view to say “Welcome To AppliedK” .
Right click on the View\Home Folder and then select Add and then View. A dialog box will appear as below.
Now we will give To AppliedK as a partial name, however by the naming convention all the partial view must be stating from underscore. The partial name will be MyPartial. Select the “Create as a Partial View” and click on add button.
We are going to add the below content code now in the partial view (MyPartial)
<h2> Hello Students </h2>
<div> Welcome to To AppliedK for new learnings </div>
How we can Include the Partial View in our Layout View?
Let us see how we can include the partial view in our layout view. We can use the @Html.Partial which is an HTML Helper that we can for including the partial view content. Pass the partial view name to @Html.Partial method as argument.
@{
ViewBag.Title = "Layout";
}
<h2>Index</h2>
@Html.Partial("MyPartial")
When we can Use the Partial View?
Partial view can be used when there are large views are available. We can effectively break up these large views into small components with the help of partial view. This can also reduce the complexity and duplicity of view. In addition to this,it allow the view to reuse.
Where TempData is Stored?
Temp data is stored in session and this is by default case. However, suppose we want to switch from default state mode to state server mode or SQL server mode then for these other modes, data should be serialized. In addition, if it is not in a serialized manner then we will be getting some session errors.
What is the need for URL rewriting?
Most sites include variables in their URLs that tell the site what information to be shown to the user. It is something like telling the code to load particular details of item number 7 from a shopping site. For example, the site may look as in the following:
http://www.cshopping.com/showitem.aspx?itemid=7
The search engines like Google cannot get any information about the content of a page from the URL. What if you wanted to convey that itemid = 7 means a laptop with brand as "DELL"? This is not saying what it should say.
So, what we expect from the preceding URL is it should be easily understandood. Will it not be good if the URL is as below?
http://www.cshopping.com/laptops/Dell/
Now looking at the preceding URL you can easily tell that it is related to laptops and the brand is DELL. So, there is a need to rewrite the URL to be somewhat meaningful and easily conveyable.
Q. How to Change URL in Browser Address Bar Without Reloading?
By using HTML5 History API in JavaScript and jQuery
HTML5 History pushState method: The pushState method works similar to window.location but it does not refresh or reload the page and it will modify the URL even if the page does not exist. The pushState method actually inserts an entry into the history of the browsers which allows us to go back and forth using the browser’s forward and back buttons. The pushState method accepts the following three parameters.
State object - The state object is a JavaScript object which can contain any details about the page and must be serializable.
Title - The title of the page.
URL – The URL of the page.
CODE: The HTML Markup consists of 3 buttons which make a call to a function ChangeUrl. This function accepts the page Title and URL as parameters. It first checks whether browser supports HTML5 and if yes then a State object containing the page Title and URL is created and is passed to the HTML5 History pushState method along with the page Title and URL as the other two parameters.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function ChangeUrl(page, url) {
if (typeof(history.pushState) != "undefined") {
var obj = { Page: page, Url: url };
history.pushState(obj, obj.Page, obj.Url);
} else {
alert("Browser does not support HTML5.");
}
}
$(function() {
$("#button1").click(function() {
ChangeUrl('Page1', 'Page1.htm');
});
$("#button2").click(function() {
ChangeUrl('Page2', 'Page2.htm');
});
$("#button3").click(function() {
ChangeUrl('Page3', 'Page3.htm');
});
});
</script>
<input type="button" value="Page1" id="button1" />
<input type="button" value="Page2" id="button2" />
<input type="button" value="Page3" id="button3" />
The HTML Markup consists of 3 buttons to which the jQuery click event handler has been assigned. Inside the jQuery click event handler, a function ChangeUrl is being called which accepts the page Title and URL as parameters.
This function first checks whether the browser supports HTML5 and if yes then a State object containing the page Title and URL is created and is passed to the HTML5 History pushStatemethod along with the Page Title and URL as the other two parameters.
https://www.c-sharpcorner.com/blogs/change-url-in-browser-address-bar-without-reloading
An Introduction To Cookies and Session Stored In TempData In ASP.NET Core
People who used TempData in ASP.NET MVC, probably knows that by default TempData is stored in a Session state. This means that the web application must have sessions enabled. Now, the ASP.NET Core 2.0 gives two TempData providers; a Cookie based and a Session State-based. This blog shows how to use both of them in an application in ASP.NET Core.
What Does Web Farm Mean?
A web farm is a collection of servers housed in a single location called a data center in order to function as a coordinated group that can be controlled and managed easily. The farm is used to accomplish needs that a single machine cannot provide such as serving a large number of people on a website or a specific application or providing more resources in a cloud environment. A web farm is also known as a server farm or a server cluster.
HomeController/Index1
public IActionResult Index1()
{
TempData[“message”] = DateTime.Now;
return View();
}
HomeController/Index2
public IActionResult Index2()
{
return View();
}
The Index1 () action stores a date-time stamp in a dictionary of TempData with a key name of the message. The Index1 view offers a hyperlink to direct to the Home/Index2. The Index2 () action gives back Index2 view. The Index2 view reads the TempData and shows the message to the user.
Index1 view is given below:
<h1>Index 1</h1>
@if (TempData.Peek(“message”) == null)
{
<h2>TempData has not been set.</h2>
}
else
{
<h2>TempData has been set.</h2>
}
<br />
<a asp-controller=”home” asp-action=”index2″>
Go to Index2
</a>
As shown the Razor code finds out whether the message has been stored in TempData or not. It does by using Peek () method of TempData. Since Peek() issued, the key won’t be removed from the TempData. And a message gets displayed in the browser mentioning the status of the message key.
When user clicks on the hyperlink given by Index1. The value of message is sent out in the browser. Markup of Index2 is given below.
<h1>Index 2</h1>
<h2>@TempData[“message”]</h2>
<br />
<a asp-controller=”home” asp-action=”index1″>
Go to Index1
</a>
Index2 reads the TempData dictionary and yields the date-time stamp value in the browser. A hyperlink permits the user to go back to the Index1.
How to know that the TempData is really using the cookies.
You need to run the application with F12 tools and locate the cookies option.
The cookie value is Base64 encoded. Since cookies are being used to store TempData all the limitations of cookie storage apply like browser support, size etc.
Session State based TempData
Let’s see how to use Session State based TempData and not the cookie based.
Session state based TempData
To allow Session state based TempData storage you must enable sessions using middleware and you also have to change the default provider. The following code shows how to do it.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession();
}
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseSession();
app.UseMvcWithDefaultRoute();
}
The ConfigureServices() calls out AddSessionStateTempDataProvider() to alter the default TempData provider to SessionStateTempDataProvider. It also summons AddSession() to allow in-memory session state for the application. The Configure() summons UseSession() to use the session state middleware.
The HomeController and its both the actions, Index1() and Index2() remains unchanged. On running the application, you can see that the final outcome will be same as before. But there won’t be any CookieTempDataProvider cookie. Instead, a Session cookie.
People who used TempData in ASP.NET MVC, probably knows that by default TempData is stored in a Session state. This means that the web application must have sessions enabled. Now, the ASP.NET Core 2.0 gives two TempData providers; a Cookie based and a Session State-based. This blog shows how to use both of them in an application in ASP.NET Core.
Serve static files from different folder than wwwroot folder in ASP.NET Core
app.UseStaticFiles() enables default web root folder wwwroot to serve the static files.
app.UseStaticFiles(new StaticFileOptions() {
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "admin")),
RequestPath = new PathString("/admin")
});
The above code configures admin folder to serve static files on the request path /admin. So now, we will be able to execute HTTP request http://localhost:1234/admin/admin.html to display static admin.html page.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-7.0
namespace Microsoft.AspNetCore.Http
QueryString
PathString
The primary interface is IFileProvider which is used to obtain file and directory information and change in them.
GetDirectoryContents(String) enumerates a directory at the given path, if any.
GetFileInfo(String) locates a file at the given path.
Watch(String) creates a IChangeToken for the specified filter.
ASP.NET Core includes dependency injection (DI) that makes configured services available throughout an app. Services are added to the DI container with WebApplicationBuilder.Services, builder.Services in the preceding code. When the WebApplicationBuilder is instantiated, many framework-provided services are added.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages(); // supports razor pages
builder.Services.AddControllersWithViews();// supports razor views
var app = builder.Build();
Services are typically resolved from DI using constructor injection. The DI framework provides an instance of this service at runtime.
Middleware The request handling pipeline is composed as a series of middleware components. Each component performs operations on an HttpContext and either invokes the next middleware in the pipeline or terminates the request.
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthorization();
app.MapGet("/hi", () => "Hello!");
app.MapDefaultControllerRoute();
app.MapRazorPages();
app.Run();
Host
On startup, an ASP.NET Core app builds a host. The host encapsulates all of the app's resources, such as:
An HTTP server implementation
Middleware components
Logging
Dependency injection (DI) services
Configuration
Types of Hosts for ASP.NET Core applications
There are three different hosts capable of running an ASP.NET Core app.
ASP.NET Core WebApplication, also known as the Minimal Host
.NET Generic Host combined with ASP.NET Core's ConfigureWebHostDefaults
ASP.NET Core WebHost
The ASP.NET Core WebApplication and WebApplicationBuilder types are recommended and used in all the ASP.NET Core templates.
The ASP.NET Core WebHost is available only for backward compatibility.
The WebApplicationBuilder.Build method configures a host with a set of default options, such as:
Use Kestrel as the web server and enable IIS integration.
Load configuration from appsettings.json, environment variables, command line arguments, and other configuration sources.
Send logging output to the console and debug providers.
Servers
An ASP.NET Core app uses an HTTP server implementation to listen for HTTP requests.
ASP.NET Core provides the following server implementations:
Kestrel is a cross-platform web server. Kestrel is often run in a reverse proxy configuration using IIS. In ASP.NET Core 2.0 or later, Kestrel can be run as a public-facing edge server exposed directly to the Internet.
IIS HTTP Server is a server for Windows that uses IIS. With this server, the ASP.NET Core app and IIS run in the same process.
HTTP.sys is a server for Windows that isn't used with IIS.
Configuration
ASP.NET Core provides a configuration framework that gets settings as name-value pairs from an ordered set of configuration providers. Built-in configuration providers are available for a variety of sources, such as .json files, .xml files, environment variables, and command-line arguments. Write custom configuration providers to support other sources.
By default, ASP.NET Core apps are configured to read from appsettings.json, environment variables, the command line, and more. When the app's configuration is loaded, values from environment variables override values from appsettings.json.
For managing confidential configuration data such as passwords, .NET Core provides the Secret Manager. For production secrets, we recommend Azure Key Vault.
In Visual Studio, right-click the project in Solution Explorer, and select Manage User Secrets from the context menu. This gesture adds a UserSecretsId element, populated with a GUID, to the project file.
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>
</PropertyGroup>
Set a secret
Define an app secret consisting of a key and its value. The secret is associated with the project's UserSecretsId value.
SON structure flattening in Visual Studio
Visual Studio's Manage User Secrets gesture opens a secrets.json file in the text editor. Replace the contents of secrets.json with the key-value pairs to be stored. For example:
{
"Movies": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=Movie-1;Trusted_Connection=True;MultipleActiveResultSets=true",
"ServiceApiKey": "12345"
}
}
Read the secret via the Configuration API
var builder = WebApplication.CreateBuilder(args);
var movieApiKey = builder.Configuration["Movies:ServiceApiKey"];
var app = builder.Build();
app.MapGet("/", () => movieApiKey);
app.Run();
Map secrets to a POCO
{
"Movies:ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=Movie-1;Trusted_Connection=True;MultipleActiveResultSets=true",
"Movies:ServiceApiKey": "12345"
}
public class MovieSettings
{
public string ConnectionString { get; set; }
public string ServiceApiKey { get; set; }
}
var moviesConfig =
Configuration.GetSection("Movies").Get<MovieSettings>();
_moviesApiKey = moviesConfig.ServiceApiKey;
Q. Explain the use of SqlConnectionStringBuilder.
The secret's value can be set on a SqlConnectionStringBuilder object's Password property to complete the connection string:
using System.Data.SqlClient;
var builder = WebApplication.CreateBuilder(args);
var conStrBuilder = new SqlConnectionStringBuilder(
builder.Configuration.GetConnectionString("Movies"));
conStrBuilder.Password = builder.Configuration["DbPassword"];
var connection = conStrBuilder.ConnectionString;
var app = builder.Build();
app.MapGet("/", () => connection);
app.Run();
List the secrets
Assume the app's secrets.json file contains the following two secrets:
{
"Movies:ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=Movie-1;Trusted_Connection=True;MultipleActiveResultSets=true",
"Movies:ServiceApiKey": "12345"
}
Run the following command from the directory in which the project file exists:
dotnet user-secrets list
The following output appears:
Movies:ConnectionString = Server=(localdb)\mssqllocaldb;Database=Movie-1;Trusted_Connection=True;MultipleActiveResultSets=true
Movies:ServiceApiKey = 12345
Manage user secrets with Visual Studio
To manage user secrets in Visual Studio, right click the project in solution explorer and select Manage User Secrets:
Environments
Execution environments, such as Development, Staging, and Production, are available in ASP.NET Core. Specify the environment an app is running in by setting the ASPNETCORE_ENVIRONMENT environment variable. ASP.NET Core reads that environment variable at app startup and stores the value in an IWebHostEnvironment implementation. This implementation is available anywhere in an app via dependency injection (DI).
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
HTTP Strict Transport Security Protocol (HSTS)
Because HSTS is enforced by the client, it has some limitations:
The client must support HSTS.
HSTS requires at least one successful HTTPS request to establish the HSTS policy.
The application must check every HTTP request and redirect or reject the HTTP request.
ASP.NET Core implements HSTS with the UseHsts extension method
builder.Services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(60);
options.ExcludedHosts.Add("example.com");
options.ExcludedHosts.Add("www.example.com");
});
UseHsts isn't recommended in development because the HSTS settings are highly cacheable by browsers. By default, UseHsts excludes the local loopback address.
For production environments that are implementing HTTPS for the first time, set the initial HstsOptions.MaxAge to a small value using one of the TimeSpan methods. Set the value from hours to no more than a single day in case you need to revert the HTTPS infrastructure to HTTP. After you're confident in the sustainability of the HTTPS configuration, increase the HSTS max-age value; a commonly used value is one year.
Explicitly sets the max-age parameter of the Strict-Transport-Security header to 60 days. If not set, defaults to 30 days.
UseHsts excludes the following loopback hosts:
localhost : The IPv4 loopback address.
127.0.0.1 : The IPv4 loopback address.
[::1] : The IPv6 loopback address.
Logging
ASP.NET Core supports a logging API that works with a variety of built-in and third-party logging providers. Available providers include:
Console
Debug
Event Tracing on Windows
Windows Event Log
TraceSource
Azure App Service
Azure Application Insights
To create logs, resolve an ILogger<TCategoryName> service from dependency injection (DI) and call logging methods such as LogInformation. For example:
public class IndexModel : PageModel
{
private readonly RazorPagesMovieContext _context;
private readonly ILogger<IndexModel> _logger;
public IndexModel(RazorPagesMovieContext context, ILogger<IndexModel> logger)
{
_context = context;
_logger = logger;
}
public IList<Movie> Movie { get;set; }
public async Task OnGetAsync()
{
_logger.LogInformation("IndexModel OnGetAsync.");
Movie = await _context.Movie.ToListAsync();
}
}
Logging providers
Logging providers store logs, except for the Console provider which displays logs. For example, the Azure Application Insights provider stores logs in Azure Application Insights. Multiple providers can be enabled.
The following code overrides the default set of logging providers added by WebApplication.CreateBuilder:
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
Alternatively, the preceding logging code can be written as follows
var builder = WebApplication.CreateBuilder();
builder.Host.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
});
Create logs
To create logs, use an ILogger<TCategoryName> object from dependency injection (DI).
The following example:
Creates a logger, ILogger<AboutModel>, which uses a log category of the fully qualified name of the type AboutModel. The log category is a string that is associated with each log.
public class AboutModel : PageModel
{
private readonly ILogger _logger;
public AboutModel(ILogger<AboutModel> logger)
{
_logger = logger;
}
public void OnGet()
{
_logger.LogInformation("About page visited at {DT}",
DateTime.UtcNow.ToLongTimeString());
}
}
Configure logging
Logging configuration is commonly provided by the Logging section of appsettings.{ENVIRONMENT}.json files, where the {ENVIRONMENT} placeholder is the environment. The following appsettings.Development.json file is generated by the ASP.NET Core web app templates:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
The "Microsoft.AspNetCore" category applies to all categories that start with "Microsoft.AspNetCore". For example, this setting applies to the "Microsoft.AspNetCore.Routing.EndpointMiddleware" category.
The "Microsoft.AspNetCore" category logs at log level Warning and higher.
A specific log provider is not specified, so LogLevel applies to all the enabled logging providers except for the Windows EventLog.
A provider property can specify a LogLevel property. LogLevel under a provider specifies levels to log for that provider, and overrides the non-provider log settings. Consider the following appsettings.json file:
{
"Logging": {
"LogLevel": { // All providers, LogLevel applies to all the enabled providers.
"Default": "Error", // Default logging, Error and higher.
"Microsoft": "Warning" // All Microsoft* categories, Warning and higher.
},
"Debug": { // Debug provider.
"LogLevel": {
"Default": "Information", // Overrides preceding LogLevel:Default setting.
"Microsoft.Hosting": "Trace" // Debug:Microsoft.Hosting category.
}
},
"EventSource": { // EventSource provider
"LogLevel": {
"Default": "Warning" // All categories of EventSource provider.
}
}
}
}
To suppress all logs, specify LogLevel.None. LogLevel.None has a value of 6, which is higher than LogLevel.Critical (5).
Log in Program.cs
The following example calls Builder.WebApplication.Logger in Program.cs and logs informational messages:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Logger.LogInformation("Adding Routes");
app.MapGet("/", () => "Hello World!");
app.Logger.LogInformation("Starting the app");
app.Run();
The following example calls AddConsole in Program.cs and logs the /Test endpoint:
var builder = WebApplication.CreateBuilder(args);
var logger = LoggerFactory.Create(config =>
{
config.AddConsole();
}).CreateLogger("Program");
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.MapGet("/Test", async context =>
{
logger.LogInformation("Testing logging in Program.cs");
await context.Response.WriteAsync("Testing");
});
app.Run();
Logging output from dotnet run and Visual Studio
Logs created with the default logging providers are displayed:
In Visual Studio
In the Debug output window when debugging.
In the ASP.NET Core Web Server window.
In the console window when the app is run with dotnet run.
Log category
When an ILogger object is created, a category is specified. That category is included with each log message created by that instance of ILogger. The category string is arbitrary, but the convention is to use the class name. For example, in a controller the name might be "TodoApi.Controllers.TodoController". The ASP.NET Core web apps use ILogger<T> to automatically get an ILogger instance that uses the fully qualified type name of T as the category:
public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;
public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}
public void OnGet()
{
_logger.LogInformation("GET Pages.PrivacyModel called.");
}
}
To explicitly specify the category, call ILoggerFactory.CreateLogger:
public class ContactModel : PageModel
{
private readonly ILogger _logger;
public ContactModel(ILoggerFactory logger)
{
_logger = logger.CreateLogger("MyCategory");
}
public void OnGet()
{
_logger.LogInformation("GET Pages.ContactModel called.");
}
Third-party logging providers
Third-party logging frameworks that work with ASP.NET Core:
elmah.io (GitHub repo)
Gelf (GitHub repo)
JSNLog (GitHub repo)
KissLog.net (GitHub repo)
Log4Net (GitHub repo)
NLog (GitHub repo)
PLogger (GitHub repo)
Sentry (GitHub repo)
Serilog (GitHub repo)
Stackdriver (Github repo)
ILogger and ILoggerFactory
The ILogger<TCategoryName> and ILoggerFactory interfaces and implementations are included in the .NET Core SDK. They are also available in the following NuGet packages:
The interfaces are in Microsoft.Extensions.Logging.Abstractions.
The default implementations are in Microsoft.Extensions.Logging.
Apply log filter rules in code
The preferred approach for setting log filter rules is by using Configuration.
The following example shows how to register filter rules in code:
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;
var builder = WebApplication.CreateBuilder();
builder.Logging.AddFilter("System", LogLevel.Debug);
builder.Logging.AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information);
builder.Logging.AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace);
NOTE logging.AddFilter("System", LogLevel.Debug) specifies the System category and log level Debug. The filter is applied to all providers because a specific provider was not configured.
AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) specifies:
The Debug logging provider.
Log level Information and higher.
All categories starting with "Microsoft".
https://learn.microsoft.com/en-us/dotnet/core/extensions/custom-logging-provider
There are many logging providers available for common logging needs. You may need to implement a custom ILoggerProvider when one of the available providers doesn't suit your application needs. In this article, you'll learn how to implement a custom logging provider that can be used to colorize logs in the console.
Sample custom logger configuration
The sample creates different color console entries per log level and event ID using the following configuration type:
using Microsoft.Extensions.Logging;
public sealed class ColorConsoleLoggerConfiguration
{
public int EventId { get; set; }
public Dictionary<LogLevel, ConsoleColor> LogLevelToColorMap { get; set; } = new()
{
[LogLevel.Information] = ConsoleColor.Green
};
}
The preceding code sets the default level to Information, the color to Green, and the EventId is implicitly 0.
Create the custom logger
The ILogger implementation category name is typically the logging source. For example, the type where the logger is created:
using Microsoft.Extensions.Logging;
public sealed class ColorConsoleLogger : ILogger
{
private readonly string _name;
private readonly Func<ColorConsoleLoggerConfiguration> _getCurrentConfig;
public ColorConsoleLogger(
string name,
Func<ColorConsoleLoggerConfiguration> getCurrentConfig) =>
(_name, _getCurrentConfig) = (name, getCurrentConfig);
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default!;
public bool IsEnabled(LogLevel logLevel) =>
_getCurrentConfig().LogLevelToColorMap.ContainsKey(logLevel);
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
ColorConsoleLoggerConfiguration config = _getCurrentConfig();
if (config.EventId == 0 || config.EventId == eventId.Id)
{
ConsoleColor originalColor = Console.ForegroundColor;
Console.ForegroundColor = config.LogLevelToColorMap[logLevel];
Console.WriteLine($"[{eventId.Id,2}: {logLevel,-12}]");
Console.ForegroundColor = originalColor;
Console.Write($" {_name} - ");
Console.ForegroundColor = config.LogLevelToColorMap[logLevel];
Console.Write($"{formatter(state, exception)}");
Console.ForegroundColor = originalColor;
Console.WriteLine();
}
}
}
Routing
A route is a URL pattern that is mapped to a handler. The handler is typically a Razor page, an action method in an MVC controller, or a middleware. ASP.NET Core routing gives you control over the URLs used by your app.
The following code, generated by the ASP.NET Core web application template, calls UseRouting:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
Check if an HttpRequest is an Ajax Request
A quick way to check if an HTTP Request is an Ajax request is by examining the X-Requested-With header value. Please see below:
bool isAjaxRequest = request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest";
public ActionResult YourActionName()
{
// Check if the request is an AJAX call
var isAjax = Request.IsAjaxRequest();
// Do something about it.
}
An, even, more common use-case for this might be, to build an ActionFilter that you could easily apply as an attribute that allows only AJAX-based requests to come through.
[AjaxOnly]
public ActionResult YourActionName()
{
// Omitted for brevity
}
Generate Random Passwords
private string GenerateRandomPassword(int minLength, int maxLength)
{
StringBuilder randomPassword = new StringBuilder();
Random rand = new Random((int)DateTime.Now.Ticks);
int randLength = rand.Next(minLength, maxLength);
for (int i = 0; i {
int charint = 0;
while (charint == 0)
charint = rand.Next(48, 58);
randomPassword.Append((char)charint); } return randomPassword.ToString();
}
}
Left, Right and Mid String Functions for C#
class LeftRightMid
{
[STAThread]
static void Main(string[] args)
{
string myString = "This is a string";
//Get 4 characters starting from the left
Console.WriteLine(Left(myString,4));
//Get 6 characters starting from the right
Console.WriteLine(Right(myString,6));
//Get 4 characters starting at index 5 of the string
Console.WriteLine(Mid(myString,5,4));
Console.ReadLine();
}
public static string Left(string param, int length)
{
string result = param.Substring(0, length);
return result;
}
public static string Right(string param, int length)
{
string result = param.Substring(param.Length - length, length);
return result;
}
public static string Mid(string param,int startIndex, int length)
{
string result = param.Substring(startIndex, length);
return result;
}
}
}
List all Environment Variables
The system variables are exposed through the GetEnvironmentVariables method available in the System.Environment class.
var environmentVariables = System.Environment.GetEnvironmentVariables();
foreach (var ev in environmentVariables)
{
DictionaryEntry de = (DictionaryEntry) ev;
Console.WriteLine(string.Format("Key: {0}, Value: {1}", de.Key, de.Value));
Console.WriteLine();
}
Q. What is HTML Agility Pack?
HAP is an HTML parser written in C# to read/write DOM and supports plain XPATH or XSLT. Look at https://html-agility-pack.net/
What's web scraping in C#?
Web scraping is a technique used in any language such as C# to extract data from a website.
Q. How can you remove all HTML tags from a string without knowing which tags are in it?
public static string StripHTML(string input)
{
return Regex.Replace(input, "<.*?>", String.Empty);
}
OR, By using HTML Agility Pack
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling </b>");
string result = htmlDoc.DocumentNode.InnerText;
Q. How can you remove all HTML tags from a string without knowing which tags are in it?Quick Way to Escape Special Characters in an XML Document
We can use the SecurityElement's Escape method of the System.Security namespace to escape all the special characters in an XML file. Code snippet below:
// let, inputXMLString contains the XML with special characters.
string escapedstring = System.Security.SecurityElement.Escape(inputXMLString);
What is difference between ContentRoot and WebRoot folder?
The ContentRoot is the folder where the application's binary resources and configuration files are saved. The WebRoot folder is the folder where the static content of web application are saved to serve the client. Static files are HTML, CSS, Images and JavaScript resources. The default web root folder name is wwwroot.
What is IFileProvider in ASP.NET Core?
IFileProvider is a base interface that is used to provide files to the ASP.NET Core web application. Files can come from different locations and so are there are various file providers. One of the common providers is a PhysicalFileProvider which is used to specify a physical disk path from which file resources are served to the application. Other providers can serve files directly from embedded resources, from a stream or from custom data providers. PhysicalFileProvider can be used for loading content out of folders other than the default wwwroot folder.
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(WebRoot),
RequestPath = new PathString("")
});
How To Change the web root folder from wwwroot to other one in ASP.NET Core
Step1. Rename the wwwroot folder to NewWebRoot.
Step2. Update the Program class with following code. The UseWebRoot method is used to change the folder.
Step2. Update the Program class with following code. The UseWebRoot method is used to change the folder.
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace WebAppMvc1
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseWebRoot("NewWebRoot");
webBuilder.UseStartup();
});
}
}
Note: The Web root folder is always inside the content root folder. If we change the content root folder also as shown below then web root folder will be inside the changed new content root folder.
webBuilder.UseContentRoot("c:\\NewContentRoot");
webBuilder.UseWebRoot("NewWebRoot");
How To Access HttpContext in ASP.NET Core
- Access HttpContext from Razor Pages. The Razor Pages PageModel exposes the PageModel.HttpContext property. The same property can be used in the corresponding Razor Page View.
- Access HttpContext from a Razor view in MVC. Razor views in the MVC pattern expose the HttpContext via the RazorPage.Context property on the view.
- Access HttpContext from a controller. Controllers expose the ControllerBase.HttpContext property.
- Access HttpContext from minimal APIs. To use HttpContext from minimal APIs, add a HttpContext parameter.
- Access HttpContext from middleware. To use HttpContext from custom middleware components, use the HttpContext parameter passed into the Invoke or InvokeAsync method of the custom middleware class.
- Access HttpContext from SignalR. To use HttpContext from SignalR, call the GetHttpContext method on Hub.Context.
- Access HttpContext from custom components. For other framework and custom components that require access to HttpContext, the recommended approach is to register a dependency using the built-in Dependency Injection (DI) container. The DI container supplies the IHttpContextAccessor to any classes that declare it as a dependency in their constructors.
How To Turn dynamic Runtime compilation On
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.0.0" />
</ItemGroup>
What are different ways to register a service of class in asp.net core?
How to create a service class in .NET Core?
How to register a service with multiple interfaces in ASP.NET Core DI?
Look at the following UseMap.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// take req delegate and return req delegate
app.Use( async (context, next) =>
{
// it doesnot use context. Just calls next middleware in pipeline
await next.Invoke();
} );
// predicate delegate,app configuration using app builder
app.UseWhen(context => !context.Request.IsHttps, builder =>
{
// some app configuration using app builder
builder.Run(ctx => ctx.Response.WriteAsync("HTTP without SSL."));
});
// predicate delegate,app configuration using app builder
app.UseWhen(context => context.Request.IsHttps, config => config.Run(context => context.Response.WriteAsync("HTTPS Request")));
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
No comments:
Post a Comment