Skip to content

Instantly share code, notes, and snippets.

View Index.cshtml
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div>
@Model.Message
</div>
<form method="post">
<div class="form-group">
View Index.cshtml.cs
using AuthenticationSample.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
View appSettings.json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"SiteUser": {
"UserName": "your user name",
"Password": "your hashed password"
View SiteUser.cs
namespace AuthenticationSample.Models
{
public class SiteUser
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
View Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(cookieOptions => {
cookieOptions.LoginPath = "/";
View Index.cshtml
@page
@model AuthenticationSample.Pages.Admin.IndexModel
@{
}
<h1>Admin</h1>
View Program.cs
using System;
using Microsoft.AspNetCore.Identity;
namespace PasswordHasherTest
{
class Program
{
static void Main(string[] args)
{
var passwordHasher = new PasswordHasher<string>();
Console.WriteLine(passwordHasher.HashPassword(null, "strong password"));
View Startup.cs
services.Configure<RouteOptions>(options =>
{
options.ConstraintMap.Add("slug", typeof(SlugParameterTransformer));
});
View SlugParameterTransformer.cs
public class SlugParameterTransformer : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
return value?.ToString().ToSlug();
}
}
View Extensions.cs
using System.Text;
public static class Extensions
{
public static string ToSlug(this string value, bool toLower = true)
{
if (value == null)
return "";
var normalised = value.Normalize(NormalizationForm.FormKD);
const int maxlen = 80;
int len = normalised.Length;