├── .gitignore ├── LICENSE ├── NotFoundMiddlewareSample.sln ├── README.md ├── global.json └── src └── NotFoundMiddlewareSample ├── .bowerrc ├── Controllers ├── AccountController.cs ├── HomeController.cs └── ManageController.cs ├── Middleware ├── BaseView.cs ├── EfNotFoundRequestRepository.cs ├── INotFoundRequestRepository.cs ├── InMemoryNotFoundRequestRepository.cs ├── NotFoundMiddleware.cs ├── NotFoundMiddlewareDbContext.cs ├── NotFoundMiddlewareOptions.cs ├── NotFoundPageMiddleware.cs ├── NotFoundRequest.cs └── RequestTracker.cs ├── Migrations ├── 00000000000000_CreateIdentitySchema.Designer.cs ├── 00000000000000_CreateIdentitySchema.cs ├── ApplicationDbContextModelSnapshot.cs └── NotFoundMiddlewareDb │ ├── 20160421002656_NotFoundRequests.Designer.cs │ ├── 20160421002656_NotFoundRequests.cs │ └── NotFoundMiddlewareDbContextModelSnapshot.cs ├── Models ├── ApplicationDbContext.cs └── ApplicationUser.cs ├── NotFoundMiddlewareSample.xproj ├── Program.cs ├── Properties └── launchSettings.json ├── Services ├── IEmailSender.cs ├── ISmsSender.cs └── MessageServices.cs ├── Startup.cs ├── ViewModels ├── Account │ ├── ExternalLoginConfirmationViewModel.cs │ ├── ForgotPasswordViewModel.cs │ ├── LoginViewModel.cs │ ├── RegisterViewModel.cs │ ├── ResetPasswordViewModel.cs │ ├── SendCodeViewModel.cs │ └── VerifyCodeViewModel.cs └── Manage │ ├── AddPhoneNumberViewModel.cs │ ├── ChangePasswordViewModel.cs │ ├── ConfigureTwoFactorViewModel.cs │ ├── FactorViewModel.cs │ ├── IndexViewModel.cs │ ├── ManageLoginsViewModel.cs │ ├── RemoveLoginViewModel.cs │ ├── SetPasswordViewModel.cs │ └── VerifyPhoneNumberViewModel.cs ├── Views ├── Account │ ├── ConfirmEmail.cshtml │ ├── ExternalLoginConfirmation.cshtml │ ├── ExternalLoginFailure.cshtml │ ├── ForgotPassword.cshtml │ ├── ForgotPasswordConfirmation.cshtml │ ├── Lockout.cshtml │ ├── Login.cshtml │ ├── Register.cshtml │ ├── ResetPassword.cshtml │ ├── ResetPasswordConfirmation.cshtml │ ├── SendCode.cshtml │ └── VerifyCode.cshtml ├── Home │ ├── About.cshtml │ ├── Contact.cshtml │ └── Index.cshtml ├── Manage │ ├── AddPhoneNumber.cshtml │ ├── ChangePassword.cshtml │ ├── Index.cshtml │ ├── ManageLogins.cshtml │ ├── SetPassword.cshtml │ └── VerifyPhoneNumber.cshtml ├── Shared │ ├── Error.cshtml │ ├── _Layout.cshtml │ ├── _LoginPartial.cshtml │ └── _ValidationScriptsPartial.cshtml ├── _ViewImports.cshtml └── _ViewStart.cshtml ├── appsettings.json ├── bower.json ├── gulpfile.js ├── package.json ├── project.json ├── web.config └── wwwroot ├── FixedLink.html ├── _references.js ├── css └── site.css ├── favicon.ico ├── images ├── ASP-NET-Banners-01.png ├── ASP-NET-Banners-02.png ├── Banner-01-Azure.png └── Banner-02-VS.png ├── js └── site.js ├── lib ├── bootstrap │ ├── .bower.json │ ├── LICENSE │ └── dist │ │ ├── css │ │ ├── bootstrap-theme.css │ │ ├── bootstrap-theme.css.map │ │ ├── bootstrap-theme.min.css │ │ ├── bootstrap.css │ │ ├── bootstrap.css.map │ │ └── bootstrap.min.css │ │ ├── fonts │ │ ├── glyphicons-halflings-regular.eot │ │ ├── glyphicons-halflings-regular.svg │ │ ├── glyphicons-halflings-regular.ttf │ │ ├── glyphicons-halflings-regular.woff │ │ └── glyphicons-halflings-regular.woff2 │ │ └── js │ │ ├── bootstrap.js │ │ ├── bootstrap.min.js │ │ └── npm.js ├── jquery-validation-unobtrusive │ ├── .bower.json │ ├── jquery.validate.unobtrusive.js │ └── jquery.validate.unobtrusive.min.js ├── jquery-validation │ ├── .bower.json │ ├── LICENSE.md │ └── dist │ │ ├── additional-methods.js │ │ ├── additional-methods.min.js │ │ ├── jquery.validate.js │ │ └── jquery.validate.min.js └── jquery │ ├── .bower.json │ ├── MIT-LICENSE.txt │ └── dist │ ├── jquery.js │ ├── jquery.min.js │ └── jquery.min.map └── web.config /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | 24 | # Visual Studio 2015 cache/options directory 25 | .vs/ 26 | # Uncomment if you have tasks that create the project's static files in wwwroot 27 | #wwwroot/ 28 | 29 | # MSTest test Results 30 | [Tt]est[Rr]esult*/ 31 | [Bb]uild[Ll]og.* 32 | 33 | # NUNIT 34 | *.VisualState.xml 35 | TestResult.xml 36 | 37 | # Build Results of an ATL Project 38 | [Dd]ebugPS/ 39 | [Rr]eleasePS/ 40 | dlldata.c 41 | 42 | # DNX 43 | project.lock.json 44 | artifacts/ 45 | 46 | *_i.c 47 | *_p.c 48 | *_i.h 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.tmp_proj 63 | *.log 64 | *.vspscc 65 | *.vssscc 66 | .builds 67 | *.pidb 68 | *.svclog 69 | *.scc 70 | 71 | # Chutzpah Test files 72 | _Chutzpah* 73 | 74 | # Visual C++ cache files 75 | ipch/ 76 | *.aps 77 | *.ncb 78 | *.opendb 79 | *.opensdf 80 | *.sdf 81 | *.cachefile 82 | 83 | # Visual Studio profiler 84 | *.psess 85 | *.vsp 86 | *.vspx 87 | *.sap 88 | 89 | # TFS 2012 Local Workspace 90 | $tf/ 91 | 92 | # Guidance Automation Toolkit 93 | *.gpState 94 | 95 | # ReSharper is a .NET coding add-in 96 | _ReSharper*/ 97 | *.[Rr]e[Ss]harper 98 | *.DotSettings.user 99 | 100 | # JustCode is a .NET coding add-in 101 | .JustCode 102 | 103 | # TeamCity is a build add-in 104 | _TeamCity* 105 | 106 | # DotCover is a Code Coverage Tool 107 | *.dotCover 108 | 109 | # NCrunch 110 | _NCrunch_* 111 | .*crunch*.local.xml 112 | nCrunchTemp_* 113 | 114 | # MightyMoose 115 | *.mm.* 116 | AutoTest.Net/ 117 | 118 | # Web workbench (sass) 119 | .sass-cache/ 120 | 121 | # Installshield output folder 122 | [Ee]xpress/ 123 | 124 | # DocProject is a documentation generator add-in 125 | DocProject/buildhelp/ 126 | DocProject/Help/*.HxT 127 | DocProject/Help/*.HxC 128 | DocProject/Help/*.hhc 129 | DocProject/Help/*.hhk 130 | DocProject/Help/*.hhp 131 | DocProject/Help/Html2 132 | DocProject/Help/html 133 | 134 | # Click-Once directory 135 | publish/ 136 | 137 | # Publish Web Output 138 | *.[Pp]ublish.xml 139 | *.azurePubxml 140 | # TODO: Comment the next line if you want to checkin your web deploy settings 141 | # but database connection strings (with potential passwords) will be unencrypted 142 | *.pubxml 143 | *.publishproj 144 | 145 | # NuGet Packages 146 | *.nupkg 147 | # The packages folder can be ignored because of Package Restore 148 | **/packages/* 149 | # except build/, which is used as an MSBuild target. 150 | !**/packages/build/ 151 | # Uncomment if necessary however generally it will be regenerated when needed 152 | #!**/packages/repositories.config 153 | # NuGet v3's project.json files produces more ignoreable files 154 | *.nuget.props 155 | *.nuget.targets 156 | 157 | # Microsoft Azure Build Output 158 | csx/ 159 | *.build.csdef 160 | 161 | # Microsoft Azure Emulator 162 | ecf/ 163 | rcf/ 164 | 165 | # Microsoft Azure ApplicationInsights config file 166 | ApplicationInsights.config 167 | 168 | # Windows Store app package directory 169 | AppPackages/ 170 | BundleArtifacts/ 171 | 172 | # Visual Studio cache files 173 | # files ending in .cache can be ignored 174 | *.[Cc]ache 175 | # but keep track of directories ending in .cache 176 | !*.[Cc]ache/ 177 | 178 | # Others 179 | ClientBin/ 180 | ~$* 181 | *~ 182 | *.dbmdl 183 | *.dbproj.schemaview 184 | *.pfx 185 | *.publishsettings 186 | node_modules/ 187 | orleans.codegen.cs 188 | 189 | # RIA/Silverlight projects 190 | Generated_Code/ 191 | 192 | # Backup & report files from converting an old project file 193 | # to a newer Visual Studio version. Backup files are not needed, 194 | # because we have git ;-) 195 | _UpgradeReport_Files/ 196 | Backup*/ 197 | UpgradeLog*.XML 198 | UpgradeLog*.htm 199 | 200 | # SQL Server files 201 | *.mdf 202 | *.ldf 203 | 204 | # Business Intelligence projects 205 | *.rdl.data 206 | *.bim.layout 207 | *.bim_*.settings 208 | 209 | # Microsoft Fakes 210 | FakesAssemblies/ 211 | 212 | # GhostDoc plugin setting file 213 | *.GhostDoc.xml 214 | 215 | # Node.js Tools for Visual Studio 216 | .ntvs_analysis.dat 217 | 218 | # Visual Studio 6 build log 219 | *.plg 220 | 221 | # Visual Studio 6 workspace options file 222 | *.opt 223 | 224 | # Visual Studio LightSwitch build output 225 | **/*.HTMLClient/GeneratedArtifacts 226 | **/*.DesktopClient/GeneratedArtifacts 227 | **/*.DesktopClient/ModelManifest.xml 228 | **/*.Server/GeneratedArtifacts 229 | **/*.Server/ModelManifest.xml 230 | _Pvt_Extensions 231 | 232 | # Paket dependency manager 233 | .paket/paket.exe 234 | 235 | # FAKE - F# Make 236 | .fake/ 237 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Steve Smith 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /NotFoundMiddlewareSample.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25123.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{96C55CEF-F17D-4025-9252-EB3C9AB4DD1B}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{BE6BAA91-B3FE-42FE-8173-FD67D2F7334A}" 9 | ProjectSection(SolutionItems) = preProject 10 | global.json = global.json 11 | EndProjectSection 12 | EndProject 13 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "NotFoundMiddlewareSample", "src\NotFoundMiddlewareSample\NotFoundMiddlewareSample.xproj", "{CA035D23-09ED-4080-8BAA-FE8E4CA6CAED}" 14 | EndProject 15 | Global 16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 17 | Debug|Any CPU = Debug|Any CPU 18 | Release|Any CPU = Release|Any CPU 19 | EndGlobalSection 20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 21 | {CA035D23-09ED-4080-8BAA-FE8E4CA6CAED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {CA035D23-09ED-4080-8BAA-FE8E4CA6CAED}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {CA035D23-09ED-4080-8BAA-FE8E4CA6CAED}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {CA035D23-09ED-4080-8BAA-FE8E4CA6CAED}.Release|Any CPU.Build.0 = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(SolutionProperties) = preSolution 27 | HideSolutionNode = FALSE 28 | EndGlobalSection 29 | GlobalSection(NestedProjects) = preSolution 30 | {CA035D23-09ED-4080-8BAA-FE8E4CA6CAED} = {96C55CEF-F17D-4025-9252-EB3C9AB4DD1B} 31 | EndGlobalSection 32 | EndGlobal 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NotFoundMiddlewareSample 2 | 3 | As described in MSDN Article: https://msdn.microsoft.com/en-us/magazine/mt707525.aspx 4 | 5 | Learn more from the [ASP.NET Core Quick Start course](http://aspnetcorequickstart.com). 6 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "projects": [ "src", "test" ] 3 | } 4 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/.bowerrc: -------------------------------------------------------------------------------- 1 | { 2 | "directory": "wwwroot/lib" 3 | } 4 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Security.Claims; 3 | using System.Threading.Tasks; 4 | using Microsoft.AspNetCore.Authorization; 5 | using Microsoft.AspNetCore.Identity; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.AspNetCore.Mvc.Rendering; 8 | using Microsoft.Extensions.Logging; 9 | using NotFoundMiddlewareSample.Models; 10 | using NotFoundMiddlewareSample.Services; 11 | using NotFoundMiddlewareSample.ViewModels.Account; 12 | 13 | namespace NotFoundMiddlewareSample.Controllers 14 | { 15 | [Authorize] 16 | public class AccountController : Controller 17 | { 18 | private readonly UserManager _userManager; 19 | private readonly SignInManager _signInManager; 20 | private readonly IEmailSender _emailSender; 21 | private readonly ISmsSender _smsSender; 22 | private readonly ILogger _logger; 23 | 24 | public AccountController( 25 | UserManager userManager, 26 | SignInManager signInManager, 27 | IEmailSender emailSender, 28 | ISmsSender smsSender, 29 | ILoggerFactory loggerFactory) 30 | { 31 | _userManager = userManager; 32 | _signInManager = signInManager; 33 | _emailSender = emailSender; 34 | _smsSender = smsSender; 35 | _logger = loggerFactory.CreateLogger(); 36 | } 37 | 38 | // 39 | // GET: /Account/Login 40 | [HttpGet] 41 | [AllowAnonymous] 42 | public IActionResult Login(string returnUrl = null) 43 | { 44 | ViewData["ReturnUrl"] = returnUrl; 45 | return View(); 46 | } 47 | 48 | // 49 | // POST: /Account/Login 50 | [HttpPost] 51 | [AllowAnonymous] 52 | [ValidateAntiForgeryToken] 53 | public async Task Login(LoginViewModel model, string returnUrl = null) 54 | { 55 | ViewData["ReturnUrl"] = returnUrl; 56 | if (ModelState.IsValid) 57 | { 58 | // This doesn't count login failures towards account lockout 59 | // To enable password failures to trigger account lockout, set lockoutOnFailure: true 60 | var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); 61 | if (result.Succeeded) 62 | { 63 | _logger.LogInformation(1, "User logged in."); 64 | return RedirectToLocal(returnUrl); 65 | } 66 | if (result.RequiresTwoFactor) 67 | { 68 | return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); 69 | } 70 | if (result.IsLockedOut) 71 | { 72 | _logger.LogWarning(2, "User account locked out."); 73 | return View("Lockout"); 74 | } 75 | else 76 | { 77 | ModelState.AddModelError(string.Empty, "Invalid login attempt."); 78 | return View(model); 79 | } 80 | } 81 | 82 | // If we got this far, something failed, redisplay form 83 | return View(model); 84 | } 85 | 86 | // 87 | // GET: /Account/Register 88 | [HttpGet] 89 | [AllowAnonymous] 90 | public IActionResult Register(string returnUrl = null) 91 | { 92 | ViewData["ReturnUrl"] = returnUrl; 93 | return View(); 94 | } 95 | 96 | // 97 | // POST: /Account/Register 98 | [HttpPost] 99 | [AllowAnonymous] 100 | [ValidateAntiForgeryToken] 101 | public async Task Register(RegisterViewModel model, string returnUrl = null) 102 | { 103 | ViewData["ReturnUrl"] = returnUrl; 104 | if (ModelState.IsValid) 105 | { 106 | var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; 107 | var result = await _userManager.CreateAsync(user, model.Password); 108 | if (result.Succeeded) 109 | { 110 | // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 111 | // Send an email with this link 112 | //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); 113 | //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); 114 | //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", 115 | // $"Please confirm your account by clicking this link: link"); 116 | await _signInManager.SignInAsync(user, isPersistent: false); 117 | _logger.LogInformation(3, "User created a new account with password."); 118 | return RedirectToLocal(returnUrl); 119 | } 120 | AddErrors(result); 121 | } 122 | 123 | // If we got this far, something failed, redisplay form 124 | return View(model); 125 | } 126 | 127 | // 128 | // POST: /Account/LogOff 129 | [HttpPost] 130 | [ValidateAntiForgeryToken] 131 | public async Task LogOff() 132 | { 133 | await _signInManager.SignOutAsync(); 134 | _logger.LogInformation(4, "User logged out."); 135 | return RedirectToAction(nameof(HomeController.Index), "Home"); 136 | } 137 | 138 | // 139 | // POST: /Account/ExternalLogin 140 | [HttpPost] 141 | [AllowAnonymous] 142 | [ValidateAntiForgeryToken] 143 | public IActionResult ExternalLogin(string provider, string returnUrl = null) 144 | { 145 | // Request a redirect to the external login provider. 146 | var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); 147 | var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); 148 | return Challenge(properties, provider); 149 | } 150 | 151 | // 152 | // GET: /Account/ExternalLoginCallback 153 | [HttpGet] 154 | [AllowAnonymous] 155 | public async Task ExternalLoginCallback(string returnUrl = null, string remoteError = null) 156 | { 157 | if (remoteError != null) 158 | { 159 | ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); 160 | return View(nameof(Login)); 161 | } 162 | var info = await _signInManager.GetExternalLoginInfoAsync(); 163 | if (info == null) 164 | { 165 | return RedirectToAction(nameof(Login)); 166 | } 167 | 168 | // Sign in the user with this external login provider if the user already has a login. 169 | var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); 170 | if (result.Succeeded) 171 | { 172 | _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); 173 | return RedirectToLocal(returnUrl); 174 | } 175 | if (result.RequiresTwoFactor) 176 | { 177 | return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); 178 | } 179 | if (result.IsLockedOut) 180 | { 181 | return View("Lockout"); 182 | } 183 | else 184 | { 185 | // If the user does not have an account, then ask the user to create an account. 186 | ViewData["ReturnUrl"] = returnUrl; 187 | ViewData["LoginProvider"] = info.LoginProvider; 188 | var email = info.Principal.FindFirstValue(ClaimTypes.Email); 189 | return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); 190 | } 191 | } 192 | 193 | // 194 | // POST: /Account/ExternalLoginConfirmation 195 | [HttpPost] 196 | [AllowAnonymous] 197 | [ValidateAntiForgeryToken] 198 | public async Task ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) 199 | { 200 | if (ModelState.IsValid) 201 | { 202 | // Get the information about the user from the external login provider 203 | var info = await _signInManager.GetExternalLoginInfoAsync(); 204 | if (info == null) 205 | { 206 | return View("ExternalLoginFailure"); 207 | } 208 | var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; 209 | var result = await _userManager.CreateAsync(user); 210 | if (result.Succeeded) 211 | { 212 | result = await _userManager.AddLoginAsync(user, info); 213 | if (result.Succeeded) 214 | { 215 | await _signInManager.SignInAsync(user, isPersistent: false); 216 | _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); 217 | return RedirectToLocal(returnUrl); 218 | } 219 | } 220 | AddErrors(result); 221 | } 222 | 223 | ViewData["ReturnUrl"] = returnUrl; 224 | return View(model); 225 | } 226 | 227 | // GET: /Account/ConfirmEmail 228 | [HttpGet] 229 | [AllowAnonymous] 230 | public async Task ConfirmEmail(string userId, string code) 231 | { 232 | if (userId == null || code == null) 233 | { 234 | return View("Error"); 235 | } 236 | var user = await _userManager.FindByIdAsync(userId); 237 | if (user == null) 238 | { 239 | return View("Error"); 240 | } 241 | var result = await _userManager.ConfirmEmailAsync(user, code); 242 | return View(result.Succeeded ? "ConfirmEmail" : "Error"); 243 | } 244 | 245 | // 246 | // GET: /Account/ForgotPassword 247 | [HttpGet] 248 | [AllowAnonymous] 249 | public IActionResult ForgotPassword() 250 | { 251 | return View(); 252 | } 253 | 254 | // 255 | // POST: /Account/ForgotPassword 256 | [HttpPost] 257 | [AllowAnonymous] 258 | [ValidateAntiForgeryToken] 259 | public async Task ForgotPassword(ForgotPasswordViewModel model) 260 | { 261 | if (ModelState.IsValid) 262 | { 263 | var user = await _userManager.FindByNameAsync(model.Email); 264 | if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) 265 | { 266 | // Don't reveal that the user does not exist or is not confirmed 267 | return View("ForgotPasswordConfirmation"); 268 | } 269 | 270 | // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 271 | // Send an email with this link 272 | //var code = await _userManager.GeneratePasswordResetTokenAsync(user); 273 | //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); 274 | //await _emailSender.SendEmailAsync(model.Email, "Reset Password", 275 | // $"Please reset your password by clicking here: link"); 276 | //return View("ForgotPasswordConfirmation"); 277 | } 278 | 279 | // If we got this far, something failed, redisplay form 280 | return View(model); 281 | } 282 | 283 | // 284 | // GET: /Account/ForgotPasswordConfirmation 285 | [HttpGet] 286 | [AllowAnonymous] 287 | public IActionResult ForgotPasswordConfirmation() 288 | { 289 | return View(); 290 | } 291 | 292 | // 293 | // GET: /Account/ResetPassword 294 | [HttpGet] 295 | [AllowAnonymous] 296 | public IActionResult ResetPassword(string code = null) 297 | { 298 | return code == null ? View("Error") : View(); 299 | } 300 | 301 | // 302 | // POST: /Account/ResetPassword 303 | [HttpPost] 304 | [AllowAnonymous] 305 | [ValidateAntiForgeryToken] 306 | public async Task ResetPassword(ResetPasswordViewModel model) 307 | { 308 | if (!ModelState.IsValid) 309 | { 310 | return View(model); 311 | } 312 | var user = await _userManager.FindByNameAsync(model.Email); 313 | if (user == null) 314 | { 315 | // Don't reveal that the user does not exist 316 | return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); 317 | } 318 | var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); 319 | if (result.Succeeded) 320 | { 321 | return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); 322 | } 323 | AddErrors(result); 324 | return View(); 325 | } 326 | 327 | // 328 | // GET: /Account/ResetPasswordConfirmation 329 | [HttpGet] 330 | [AllowAnonymous] 331 | public IActionResult ResetPasswordConfirmation() 332 | { 333 | return View(); 334 | } 335 | 336 | // 337 | // GET: /Account/SendCode 338 | [HttpGet] 339 | [AllowAnonymous] 340 | public async Task SendCode(string returnUrl = null, bool rememberMe = false) 341 | { 342 | var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); 343 | if (user == null) 344 | { 345 | return View("Error"); 346 | } 347 | var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); 348 | var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); 349 | return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); 350 | } 351 | 352 | // 353 | // POST: /Account/SendCode 354 | [HttpPost] 355 | [AllowAnonymous] 356 | [ValidateAntiForgeryToken] 357 | public async Task SendCode(SendCodeViewModel model) 358 | { 359 | if (!ModelState.IsValid) 360 | { 361 | return View(); 362 | } 363 | 364 | var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); 365 | if (user == null) 366 | { 367 | return View("Error"); 368 | } 369 | 370 | // Generate the token and send it 371 | var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); 372 | if (string.IsNullOrWhiteSpace(code)) 373 | { 374 | return View("Error"); 375 | } 376 | 377 | var message = "Your security code is: " + code; 378 | if (model.SelectedProvider == "Email") 379 | { 380 | await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); 381 | } 382 | else if (model.SelectedProvider == "Phone") 383 | { 384 | await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); 385 | } 386 | 387 | return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); 388 | } 389 | 390 | // 391 | // GET: /Account/VerifyCode 392 | [HttpGet] 393 | [AllowAnonymous] 394 | public async Task VerifyCode(string provider, bool rememberMe, string returnUrl = null) 395 | { 396 | // Require that the user has already logged in via username/password or external login 397 | var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); 398 | if (user == null) 399 | { 400 | return View("Error"); 401 | } 402 | return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); 403 | } 404 | 405 | // 406 | // POST: /Account/VerifyCode 407 | [HttpPost] 408 | [AllowAnonymous] 409 | [ValidateAntiForgeryToken] 410 | public async Task VerifyCode(VerifyCodeViewModel model) 411 | { 412 | if (!ModelState.IsValid) 413 | { 414 | return View(model); 415 | } 416 | 417 | // The following code protects for brute force attacks against the two factor codes. 418 | // If a user enters incorrect codes for a specified amount of time then the user account 419 | // will be locked out for a specified amount of time. 420 | var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); 421 | if (result.Succeeded) 422 | { 423 | return RedirectToLocal(model.ReturnUrl); 424 | } 425 | if (result.IsLockedOut) 426 | { 427 | _logger.LogWarning(7, "User account locked out."); 428 | return View("Lockout"); 429 | } 430 | else 431 | { 432 | ModelState.AddModelError(string.Empty, "Invalid code."); 433 | return View(model); 434 | } 435 | } 436 | 437 | #region Helpers 438 | 439 | private void AddErrors(IdentityResult result) 440 | { 441 | foreach (var error in result.Errors) 442 | { 443 | ModelState.AddModelError(string.Empty, error.Description); 444 | } 445 | } 446 | 447 | private Task GetCurrentUserAsync() 448 | { 449 | return _userManager.GetUserAsync(HttpContext.User); 450 | } 451 | 452 | private IActionResult RedirectToLocal(string returnUrl) 453 | { 454 | if (Url.IsLocalUrl(returnUrl)) 455 | { 456 | return Redirect(returnUrl); 457 | } 458 | else 459 | { 460 | return RedirectToAction(nameof(HomeController.Index), "Home"); 461 | } 462 | } 463 | 464 | #endregion 465 | } 466 | } 467 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace NotFoundMiddlewareSample.Controllers 4 | { 5 | public class HomeController : Controller 6 | { 7 | public IActionResult Index() 8 | { 9 | return View(); 10 | } 11 | 12 | public IActionResult About() 13 | { 14 | ViewData["Message"] = "Your application description page."; 15 | 16 | return View(); 17 | } 18 | 19 | public IActionResult Contact() 20 | { 21 | ViewData["Message"] = "Your contact page."; 22 | 23 | return View(); 24 | } 25 | 26 | public IActionResult Error() 27 | { 28 | return View(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Controllers/ManageController.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Identity; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.Logging; 7 | using NotFoundMiddlewareSample.Models; 8 | using NotFoundMiddlewareSample.Services; 9 | using NotFoundMiddlewareSample.ViewModels.Manage; 10 | 11 | namespace NotFoundMiddlewareSample.Controllers 12 | { 13 | [Authorize] 14 | public class ManageController : Controller 15 | { 16 | private readonly UserManager _userManager; 17 | private readonly SignInManager _signInManager; 18 | private readonly IEmailSender _emailSender; 19 | private readonly ISmsSender _smsSender; 20 | private readonly ILogger _logger; 21 | 22 | public ManageController( 23 | UserManager userManager, 24 | SignInManager signInManager, 25 | IEmailSender emailSender, 26 | ISmsSender smsSender, 27 | ILoggerFactory loggerFactory) 28 | { 29 | _userManager = userManager; 30 | _signInManager = signInManager; 31 | _emailSender = emailSender; 32 | _smsSender = smsSender; 33 | _logger = loggerFactory.CreateLogger(); 34 | } 35 | 36 | // 37 | // GET: /Manage/Index 38 | [HttpGet] 39 | public async Task Index(ManageMessageId? message = null) 40 | { 41 | ViewData["StatusMessage"] = 42 | message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." 43 | : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." 44 | : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." 45 | : message == ManageMessageId.Error ? "An error has occurred." 46 | : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." 47 | : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." 48 | : ""; 49 | 50 | var user = await GetCurrentUserAsync(); 51 | var model = new IndexViewModel 52 | { 53 | HasPassword = await _userManager.HasPasswordAsync(user), 54 | PhoneNumber = await _userManager.GetPhoneNumberAsync(user), 55 | TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), 56 | Logins = await _userManager.GetLoginsAsync(user), 57 | BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) 58 | }; 59 | return View(model); 60 | } 61 | 62 | // 63 | // POST: /Manage/RemoveLogin 64 | [HttpPost] 65 | [ValidateAntiForgeryToken] 66 | public async Task RemoveLogin(RemoveLoginViewModel account) 67 | { 68 | ManageMessageId? message = ManageMessageId.Error; 69 | var user = await GetCurrentUserAsync(); 70 | if (user != null) 71 | { 72 | var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); 73 | if (result.Succeeded) 74 | { 75 | await _signInManager.SignInAsync(user, isPersistent: false); 76 | message = ManageMessageId.RemoveLoginSuccess; 77 | } 78 | } 79 | return RedirectToAction(nameof(ManageLogins), new { Message = message }); 80 | } 81 | 82 | // 83 | // GET: /Manage/AddPhoneNumber 84 | public IActionResult AddPhoneNumber() 85 | { 86 | return View(); 87 | } 88 | 89 | // 90 | // POST: /Manage/AddPhoneNumber 91 | [HttpPost] 92 | [ValidateAntiForgeryToken] 93 | public async Task AddPhoneNumber(AddPhoneNumberViewModel model) 94 | { 95 | if (!ModelState.IsValid) 96 | { 97 | return View(model); 98 | } 99 | // Generate the token and send it 100 | var user = await GetCurrentUserAsync(); 101 | var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); 102 | await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code); 103 | return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); 104 | } 105 | 106 | // 107 | // POST: /Manage/EnableTwoFactorAuthentication 108 | [HttpPost] 109 | [ValidateAntiForgeryToken] 110 | public async Task EnableTwoFactorAuthentication() 111 | { 112 | var user = await GetCurrentUserAsync(); 113 | if (user != null) 114 | { 115 | await _userManager.SetTwoFactorEnabledAsync(user, true); 116 | await _signInManager.SignInAsync(user, isPersistent: false); 117 | _logger.LogInformation(1, "User enabled two-factor authentication."); 118 | } 119 | return RedirectToAction(nameof(Index), "Manage"); 120 | } 121 | 122 | // 123 | // POST: /Manage/DisableTwoFactorAuthentication 124 | [HttpPost] 125 | [ValidateAntiForgeryToken] 126 | public async Task DisableTwoFactorAuthentication() 127 | { 128 | var user = await GetCurrentUserAsync(); 129 | if (user != null) 130 | { 131 | await _userManager.SetTwoFactorEnabledAsync(user, false); 132 | await _signInManager.SignInAsync(user, isPersistent: false); 133 | _logger.LogInformation(2, "User disabled two-factor authentication."); 134 | } 135 | return RedirectToAction(nameof(Index), "Manage"); 136 | } 137 | 138 | // 139 | // GET: /Manage/VerifyPhoneNumber 140 | [HttpGet] 141 | public async Task VerifyPhoneNumber(string phoneNumber) 142 | { 143 | var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); 144 | // Send an SMS to verify the phone number 145 | return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); 146 | } 147 | 148 | // 149 | // POST: /Manage/VerifyPhoneNumber 150 | [HttpPost] 151 | [ValidateAntiForgeryToken] 152 | public async Task VerifyPhoneNumber(VerifyPhoneNumberViewModel model) 153 | { 154 | if (!ModelState.IsValid) 155 | { 156 | return View(model); 157 | } 158 | var user = await GetCurrentUserAsync(); 159 | if (user != null) 160 | { 161 | var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); 162 | if (result.Succeeded) 163 | { 164 | await _signInManager.SignInAsync(user, isPersistent: false); 165 | return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); 166 | } 167 | } 168 | // If we got this far, something failed, redisplay the form 169 | ModelState.AddModelError(string.Empty, "Failed to verify phone number"); 170 | return View(model); 171 | } 172 | 173 | // 174 | // POST: /Manage/RemovePhoneNumber 175 | [HttpPost] 176 | [ValidateAntiForgeryToken] 177 | public async Task RemovePhoneNumber() 178 | { 179 | var user = await GetCurrentUserAsync(); 180 | if (user != null) 181 | { 182 | var result = await _userManager.SetPhoneNumberAsync(user, null); 183 | if (result.Succeeded) 184 | { 185 | await _signInManager.SignInAsync(user, isPersistent: false); 186 | return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); 187 | } 188 | } 189 | return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); 190 | } 191 | 192 | // 193 | // GET: /Manage/ChangePassword 194 | [HttpGet] 195 | public IActionResult ChangePassword() 196 | { 197 | return View(); 198 | } 199 | 200 | // 201 | // POST: /Manage/ChangePassword 202 | [HttpPost] 203 | [ValidateAntiForgeryToken] 204 | public async Task ChangePassword(ChangePasswordViewModel model) 205 | { 206 | if (!ModelState.IsValid) 207 | { 208 | return View(model); 209 | } 210 | var user = await GetCurrentUserAsync(); 211 | if (user != null) 212 | { 213 | var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); 214 | if (result.Succeeded) 215 | { 216 | await _signInManager.SignInAsync(user, isPersistent: false); 217 | _logger.LogInformation(3, "User changed their password successfully."); 218 | return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); 219 | } 220 | AddErrors(result); 221 | return View(model); 222 | } 223 | return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); 224 | } 225 | 226 | // 227 | // GET: /Manage/SetPassword 228 | [HttpGet] 229 | public IActionResult SetPassword() 230 | { 231 | return View(); 232 | } 233 | 234 | // 235 | // POST: /Manage/SetPassword 236 | [HttpPost] 237 | [ValidateAntiForgeryToken] 238 | public async Task SetPassword(SetPasswordViewModel model) 239 | { 240 | if (!ModelState.IsValid) 241 | { 242 | return View(model); 243 | } 244 | 245 | var user = await GetCurrentUserAsync(); 246 | if (user != null) 247 | { 248 | var result = await _userManager.AddPasswordAsync(user, model.NewPassword); 249 | if (result.Succeeded) 250 | { 251 | await _signInManager.SignInAsync(user, isPersistent: false); 252 | return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); 253 | } 254 | AddErrors(result); 255 | return View(model); 256 | } 257 | return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); 258 | } 259 | 260 | //GET: /Manage/ManageLogins 261 | [HttpGet] 262 | public async Task ManageLogins(ManageMessageId? message = null) 263 | { 264 | ViewData["StatusMessage"] = 265 | message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." 266 | : message == ManageMessageId.AddLoginSuccess ? "The external login was added." 267 | : message == ManageMessageId.Error ? "An error has occurred." 268 | : ""; 269 | var user = await GetCurrentUserAsync(); 270 | if (user == null) 271 | { 272 | return View("Error"); 273 | } 274 | var userLogins = await _userManager.GetLoginsAsync(user); 275 | var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList(); 276 | ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; 277 | return View(new ManageLoginsViewModel 278 | { 279 | CurrentLogins = userLogins, 280 | OtherLogins = otherLogins 281 | }); 282 | } 283 | 284 | // 285 | // POST: /Manage/LinkLogin 286 | [HttpPost] 287 | [ValidateAntiForgeryToken] 288 | public IActionResult LinkLogin(string provider) 289 | { 290 | // Request a redirect to the external login provider to link a login for the current user 291 | var redirectUrl = Url.Action("LinkLoginCallback", "Manage"); 292 | var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); 293 | return Challenge(properties, provider); 294 | } 295 | 296 | // 297 | // GET: /Manage/LinkLoginCallback 298 | [HttpGet] 299 | public async Task LinkLoginCallback() 300 | { 301 | var user = await GetCurrentUserAsync(); 302 | if (user == null) 303 | { 304 | return View("Error"); 305 | } 306 | var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); 307 | if (info == null) 308 | { 309 | return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); 310 | } 311 | var result = await _userManager.AddLoginAsync(user, info); 312 | var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error; 313 | return RedirectToAction(nameof(ManageLogins), new { Message = message }); 314 | } 315 | 316 | #region Helpers 317 | 318 | private void AddErrors(IdentityResult result) 319 | { 320 | foreach (var error in result.Errors) 321 | { 322 | ModelState.AddModelError(string.Empty, error.Description); 323 | } 324 | } 325 | 326 | public enum ManageMessageId 327 | { 328 | AddPhoneSuccess, 329 | AddLoginSuccess, 330 | ChangePasswordSuccess, 331 | SetTwoFactorSuccess, 332 | SetPasswordSuccess, 333 | RemoveLoginSuccess, 334 | RemovePhoneSuccess, 335 | Error 336 | } 337 | 338 | private Task GetCurrentUserAsync() 339 | { 340 | return _userManager.GetUserAsync(HttpContext.User); 341 | } 342 | 343 | #endregion 344 | } 345 | } 346 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/BaseView.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Globalization; 5 | using System.IO; 6 | using System.Text; 7 | using System.Text.Encodings.Web; 8 | using System.Threading.Tasks; 9 | using Microsoft.AspNetCore.Http; 10 | 11 | namespace NotFoundMiddlewareSample.Middleware 12 | { 13 | public abstract class BaseView 14 | { 15 | /// 16 | /// The request context 17 | /// 18 | protected HttpContext Context { get; private set; } 19 | 20 | /// 21 | /// The request 22 | /// 23 | protected HttpRequest Request { get; private set; } 24 | 25 | /// 26 | /// The response 27 | /// 28 | protected HttpResponse Response { get; private set; } 29 | 30 | /// 31 | /// The output stream 32 | /// 33 | protected StreamWriter Output { get; private set; } 34 | 35 | /// 36 | /// Html encoder used to encode content. 37 | /// 38 | protected HtmlEncoder HtmlEncoder { get; set; } = HtmlEncoder.Default; 39 | 40 | /// 41 | /// Url encoder used to encode content. 42 | /// 43 | protected UrlEncoder UrlEncoder { get; set; } = UrlEncoder.Default; 44 | 45 | /// 46 | /// Execute an individual request 47 | /// 48 | /// 49 | public async Task ExecuteAsync(HttpContext context) 50 | { 51 | Context = context; 52 | Request = Context.Request; 53 | Response = Context.Response; 54 | Output = new StreamWriter(Response.Body, Encoding.UTF8, 4096, leaveOpen: true); 55 | await ExecuteAsync(); 56 | Output.Dispose(); 57 | } 58 | 59 | /// 60 | /// Execute an individual request 61 | /// 62 | public abstract Task ExecuteAsync(); 63 | 64 | /// 65 | /// Write the given value directly to the output 66 | /// 67 | /// 68 | protected void WriteLiteral(string value) 69 | { 70 | WriteLiteralTo(Output, value); 71 | } 72 | 73 | /// 74 | /// Write the given value directly to the output 75 | /// 76 | /// 77 | protected void WriteLiteral(object value) 78 | { 79 | WriteLiteralTo(Output, value); 80 | } 81 | 82 | private List AttributeValues { get; set; } 83 | 84 | protected void WriteAttributeValue(string thingy, int startPostion, object value, int endValue, int dealyo, bool yesno) 85 | { 86 | if (AttributeValues == null) 87 | { 88 | AttributeValues = new List(); 89 | } 90 | 91 | AttributeValues.Add(value.ToString()); 92 | } 93 | 94 | private string AttributeEnding { get; set; } 95 | 96 | protected void BeginWriteAttribute(string name, string begining, int startPosition, string ending, int endPosition, int thingy) 97 | { 98 | Debug.Assert(string.IsNullOrEmpty(AttributeEnding)); 99 | 100 | Output.Write(begining); 101 | AttributeEnding = ending; 102 | } 103 | 104 | protected void EndWriteAttribute() 105 | { 106 | Debug.Assert(!string.IsNullOrEmpty(AttributeEnding)); 107 | 108 | var attributes = string.Join(" ", AttributeValues); 109 | Output.Write(attributes); 110 | AttributeValues = null; 111 | 112 | Output.Write(AttributeEnding); 113 | AttributeEnding = null; 114 | } 115 | 116 | ///// 117 | ///// Writes the given attribute to the given writer 118 | ///// 119 | ///// The instance to write to. 120 | ///// The name of the attribute to write 121 | ///// The value of the prefix 122 | ///// The value of the suffix 123 | ///// The s to write. 124 | //protected void WriteAttributeTo( 125 | // TextWriter writer, 126 | // string name, 127 | // string leader, 128 | // string trailer, 129 | // params Microsoft.AspNetCore.DiagnosticsViewPage.Views.AttributeValue[] values) 130 | // See bug https://github.com/aspnet/Diagnostics/issues/295 131 | //{ 132 | // if (writer == null) 133 | // { 134 | // throw new ArgumentNullException(nameof(writer)); 135 | // } 136 | 137 | // if (name == null) 138 | // { 139 | // throw new ArgumentNullException(nameof(name)); 140 | // } 141 | 142 | // if (leader == null) 143 | // { 144 | // throw new ArgumentNullException(nameof(leader)); 145 | // } 146 | 147 | // if (trailer == null) 148 | // { 149 | // throw new ArgumentNullException(nameof(trailer)); 150 | // } 151 | 152 | 153 | // WriteLiteralTo(writer, leader); 154 | // foreach (var value in values) 155 | // { 156 | // WriteLiteralTo(writer, value.Prefix); 157 | 158 | // // The special cases here are that the value we're writing might already be a string, or that the 159 | // // value might be a bool. If the value is the bool 'true' we want to write the attribute name 160 | // // instead of the string 'true'. If the value is the bool 'false' we don't want to write anything. 161 | // // Otherwise the value is another object (perhaps an HtmlString) and we'll ask it to format itself. 162 | // string stringValue; 163 | // if (value.Value is bool) 164 | // { 165 | // if ((bool)value.Value) 166 | // { 167 | // stringValue = name; 168 | // } 169 | // else 170 | // { 171 | // continue; 172 | // } 173 | // } 174 | // else 175 | // { 176 | // stringValue = value.Value as string; 177 | // } 178 | 179 | // // Call the WriteTo(string) overload when possible 180 | // if (value.Literal && stringValue != null) 181 | // { 182 | // WriteLiteralTo(writer, stringValue); 183 | // } 184 | // else if (value.Literal) 185 | // { 186 | // WriteLiteralTo(writer, value.Value); 187 | // } 188 | // else if (stringValue != null) 189 | // { 190 | // WriteTo(writer, stringValue); 191 | // } 192 | // else 193 | // { 194 | // WriteTo(writer, value.Value); 195 | // } 196 | // } 197 | // WriteLiteralTo(writer, trailer); 198 | //} 199 | 200 | /// 201 | /// Convert to string and html encode 202 | /// 203 | /// 204 | protected void Write(object value) 205 | { 206 | WriteTo(Output, value); 207 | } 208 | 209 | /// 210 | /// Html encode and write 211 | /// 212 | /// 213 | protected void Write(string value) 214 | { 215 | WriteTo(Output, value); 216 | } 217 | 218 | /// 219 | /// is invoked 220 | /// 221 | /// The to invoke 222 | protected void Write(Microsoft.AspNetCore.Mvc.Razor.HelperResult result) 223 | { 224 | WriteTo(Output, result); 225 | } 226 | 227 | /// 228 | /// Writes the specified to . 229 | /// 230 | /// The instance to write to. 231 | /// The to write. 232 | /// 233 | /// is invoked for types. 234 | /// For all other types, the encoded result of is written to the 235 | /// . 236 | /// 237 | protected void WriteTo(TextWriter writer, object value) 238 | { 239 | if (value != null) 240 | { 241 | var helperResult = value as Microsoft.AspNetCore.Mvc.Razor.HelperResult; 242 | if (helperResult != null) 243 | { 244 | helperResult.WriteTo(writer, HtmlEncoder); 245 | } 246 | else 247 | { 248 | WriteTo(writer, Convert.ToString(value, CultureInfo.InvariantCulture)); 249 | } 250 | } 251 | } 252 | 253 | /// 254 | /// Writes the specified with HTML encoding to . 255 | /// 256 | /// The instance to write to. 257 | /// The to write. 258 | protected void WriteTo(TextWriter writer, string value) 259 | { 260 | WriteLiteralTo(writer, HtmlEncoder.Encode(value)); 261 | } 262 | 263 | /// 264 | /// Writes the specified without HTML encoding to the . 265 | /// 266 | /// The instance to write to. 267 | /// The to write. 268 | protected void WriteLiteralTo(TextWriter writer, object value) 269 | { 270 | WriteLiteralTo(writer, Convert.ToString(value, CultureInfo.InvariantCulture)); 271 | } 272 | 273 | /// 274 | /// Writes the specified without HTML encoding to . 275 | /// 276 | /// The instance to write to. 277 | /// The to write. 278 | protected void WriteLiteralTo(TextWriter writer, string value) 279 | { 280 | if (!string.IsNullOrEmpty(value)) 281 | { 282 | writer.Write(value); 283 | } 284 | } 285 | 286 | //protected string HtmlEncodeAndReplaceLineBreaks(string input) 287 | //{ 288 | // if (string.IsNullOrEmpty(input)) 289 | // { 290 | // return string.Empty; 291 | // } 292 | 293 | // // Split on line breaks before passing it through the encoder. 294 | // return string.Join("
" + Environment.NewLine, 295 | // input.Split(new[] { "\r\n" }, StringSplitOptions.None) 296 | // .SelectMany(s => s.Split(new[] { '\r', '\n' }, StringSplitOptions.None)) 297 | // .Select(HtmlEncoder.Encode)); 298 | //} 299 | } 300 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/EfNotFoundRequestRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.EntityFrameworkCore; 3 | using System.Linq; 4 | 5 | namespace NotFoundMiddlewareSample.Middleware 6 | { 7 | public class EfNotFoundRequestRepository : INotFoundRequestRepository 8 | { 9 | private readonly NotFoundMiddlewareDbContext _dbContext; 10 | 11 | public EfNotFoundRequestRepository(NotFoundMiddlewareDbContext dbContext) 12 | { 13 | _dbContext = dbContext; 14 | } 15 | 16 | public NotFoundRequest GetByPath(string path) 17 | { 18 | return _dbContext.NotFoundRequests 19 | .FirstOrDefault(r => r.Path == path.ToLowerInvariant()); 20 | } 21 | 22 | public IEnumerable List() 23 | { 24 | return _dbContext.NotFoundRequests.AsEnumerable(); 25 | } 26 | 27 | public void Update(NotFoundRequest notFoundRequest) 28 | { 29 | _dbContext.Entry(notFoundRequest).State = EntityState.Modified; 30 | _dbContext.SaveChanges(); 31 | } 32 | 33 | public void Add(NotFoundRequest notFoundRequest) 34 | { 35 | _dbContext.NotFoundRequests.Add(notFoundRequest); 36 | _dbContext.SaveChanges(); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/INotFoundRequestRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace NotFoundMiddlewareSample.Middleware 4 | { 5 | public interface INotFoundRequestRepository 6 | { 7 | NotFoundRequest GetByPath(string path); 8 | IEnumerable List(); 9 | void Update(NotFoundRequest notFoundRequest); 10 | void Add(NotFoundRequest notFoundRequest); 11 | } 12 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/InMemoryNotFoundRequestRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace NotFoundMiddlewareSample.Middleware 5 | { 6 | public class InMemoryNotFoundRequestRepository : INotFoundRequestRepository 7 | { 8 | private static Dictionary _requests = new Dictionary(); 9 | 10 | public NotFoundRequest GetByPath(string path) 11 | { 12 | if (_requests.ContainsKey(path)) 13 | { 14 | return _requests[path]; 15 | } 16 | return null; 17 | } 18 | 19 | public IEnumerable List() 20 | { 21 | return _requests.Values.OrderByDescending(r => r.Count); 22 | } 23 | 24 | public void Update(NotFoundRequest notFoundRequest) 25 | { 26 | if (_requests.ContainsKey(notFoundRequest.Path)) 27 | { 28 | _requests[notFoundRequest.Path] = notFoundRequest; 29 | } 30 | } 31 | 32 | public void Add(NotFoundRequest notFoundRequest) 33 | { 34 | if (!_requests.ContainsKey(notFoundRequest.Path)) 35 | { 36 | _requests.Add(notFoundRequest.Path, notFoundRequest); 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/NotFoundMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Logging; 7 | using Microsoft.Extensions.Options; 8 | 9 | namespace NotFoundMiddlewareSample.Middleware 10 | { 11 | // You may need to install the Microsoft.AspNet.Http.Abstractions package into your project 12 | public class NotFoundMiddleware 13 | { 14 | private readonly RequestDelegate _next; 15 | private readonly RequestTracker _requestTracker; 16 | private readonly ILogger _logger; 17 | private NotFoundMiddlewareOptions _options; 18 | 19 | public NotFoundMiddleware(RequestDelegate next, 20 | ILoggerFactory loggerFactory, 21 | RequestTracker requestTracker, 22 | IOptions options) 23 | { 24 | _next = next; 25 | _requestTracker = requestTracker; 26 | _logger = loggerFactory.CreateLogger(); 27 | _options = options.Value; 28 | } 29 | 30 | public async Task Invoke(HttpContext httpContext) 31 | { 32 | string path = httpContext.Request.Path; 33 | _logger.LogTrace("Path: {path}"); 34 | string correctedPath = _requestTracker.GetRequest(path)?.CorrectedPath; 35 | if (correctedPath != null) 36 | { 37 | if (_options.FixPathBehavior == FixPathBehavior.Redirect) 38 | { 39 | string fullPath = httpContext.Request.PathBase + 40 | correctedPath + httpContext.Request.QueryString; 41 | _logger.LogTrace("Redirecting to: {fullPath}"); 42 | httpContext.Response.Redirect(fullPath, permanent: true); 43 | return; 44 | } 45 | if (_options.FixPathBehavior == FixPathBehavior.Rewrite) 46 | { 47 | _logger.LogTrace("Rewriting path to: {correctedPath}"); 48 | httpContext.Request.Path = correctedPath; // rewrite the path 49 | } 50 | // throw invalid operation exception 51 | } 52 | await _next(httpContext); 53 | if (httpContext.Response.StatusCode == 404) 54 | { 55 | _logger.LogTrace("Recording 404: {httpContext.Request.Path}"); 56 | _requestTracker.Record(httpContext.Request.Path); // NOTE: might not be same as original path at this point 57 | } 58 | } 59 | } 60 | 61 | // Extension method used to add the middleware to the HTTP request pipeline. 62 | public static class NotFoundMiddlewareExtensions 63 | { 64 | public static IApplicationBuilder UseNotFoundMiddleware(this IApplicationBuilder builder) 65 | { 66 | return builder.UseMiddleware(); 67 | } 68 | 69 | public static IServiceCollection AddNotFoundMiddlewareInMemory(this IServiceCollection services) 70 | { 71 | services.AddSingleton(); 72 | return services.AddSingleton(); 73 | } 74 | public static IServiceCollection AddNotFoundMiddlewareEntityFramework( 75 | this IServiceCollection services, string connectionString) 76 | { 77 | services.AddDbContext(options => 78 | options.UseSqlServer(connectionString)); 79 | 80 | services.AddSingleton(); 81 | return services.AddSingleton(); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/NotFoundMiddlewareDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace NotFoundMiddlewareSample.Middleware 4 | { 5 | public class NotFoundMiddlewareDbContext : DbContext 6 | { 7 | public NotFoundMiddlewareDbContext(DbContextOptions options) 8 | : base(options) 9 | { 10 | } 11 | 12 | public DbSet NotFoundRequests { get; set; } 13 | protected override void OnModelCreating(ModelBuilder modelBuilder) 14 | { 15 | base.OnModelCreating(modelBuilder); 16 | modelBuilder.Entity() 17 | .ToTable("NotFoundRequest") 18 | .HasKey(r => r.Path); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/NotFoundMiddlewareOptions.cs: -------------------------------------------------------------------------------- 1 | namespace NotFoundMiddlewareSample.Middleware 2 | { 3 | public enum FixPathBehavior 4 | { 5 | Redirect, 6 | Rewrite 7 | } 8 | 9 | public class NotFoundMiddlewareOptions 10 | { 11 | public string Path { get; set; } = "/fix404s"; 12 | public FixPathBehavior FixPathBehavior { get; set; } = FixPathBehavior.Redirect; 13 | } 14 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/NotFoundPageMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Http; 7 | using Microsoft.Extensions.Logging; 8 | using Microsoft.Extensions.Options; 9 | 10 | namespace NotFoundMiddlewareSample.Middleware 11 | { 12 | public class NotFoundPageMiddleware 13 | { 14 | private readonly RequestDelegate _next; 15 | private readonly RequestTracker _requestTracker; 16 | private readonly ILogger _logger; 17 | private readonly NotFoundMiddlewareOptions _options; 18 | 19 | public NotFoundPageMiddleware(RequestDelegate next, 20 | ILoggerFactory loggerFactory, 21 | RequestTracker requestTracker, 22 | IOptions options) 23 | { 24 | _next = next; 25 | _requestTracker = requestTracker; 26 | _logger = loggerFactory.CreateLogger(); 27 | _options = options.Value; 28 | } 29 | 30 | public async Task Invoke(HttpContext httpContext) 31 | { 32 | if (!httpContext.Request.Path.StartsWithSegments(_options.Path)) 33 | { 34 | await _next(httpContext); 35 | return; 36 | } 37 | if (httpContext.Request.Query.Keys.Contains("path") && 38 | httpContext.Request.Query.Keys.Contains("fixedpath")) 39 | { 40 | var request = _requestTracker.GetRequest(httpContext.Request.Query["path"]); 41 | request.SetCorrectedPath(httpContext.Request.Query["fixedpath"]); 42 | _requestTracker.UpdateRequest(request); 43 | } 44 | Render404List(httpContext); 45 | } 46 | 47 | private async void Render404List(HttpContext httpContext) 48 | { 49 | var model = _requestTracker.ListRequests() 50 | .OrderByDescending(r => r.Count); 51 | var requestPage = new RequestPage(model); 52 | await requestPage.ExecuteAsync(httpContext); 53 | } 54 | } 55 | 56 | // Extension method used to add the middleware to the HTTP request pipeline. 57 | public static class NotFoundPageMiddlewareExtensions 58 | { 59 | public static IApplicationBuilder UseNotFoundPageMiddleware(this IApplicationBuilder builder) 60 | { 61 | return builder.UseMiddleware(); 62 | } 63 | } 64 | 65 | public class RequestPage : BaseView 66 | { 67 | private readonly IEnumerable _requests; 68 | 69 | public RequestPage(IEnumerable requests) 70 | { 71 | _requests = requests; 72 | } 73 | 74 | public override async Task ExecuteAsync() 75 | { 76 | WriteLiteral("\r\n"); 77 | Response.ContentType = "text/html"; 78 | WriteLiteral(@" 79 | 80 | 81 | 82 | 83 | Fix 404s 84 | 85 | 228 | 229 | 230 |

Fix 404s

"); 231 | // render requests 232 | WriteLiteral(@" 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | "); 241 | foreach (var request in _requests) 242 | { 243 | WriteLiteral(@""); 244 | WriteLiteral($""); 245 | if (!String.IsNullOrEmpty(request.CorrectedPath)) 246 | { 247 | WriteLiteral($""); 248 | } 249 | else 250 | { // TODO: UrlEncode request.Path 251 | WriteLiteral(@""); 252 | } 253 | WriteLiteral(""); 254 | } 255 | 256 | WriteLiteral(@" 257 | 258 |
Path404 CountCorrected Path
{request.Path}{request.Count}{ request.CorrectedPath} Save
259 | 269 | 270 | 271 | "); 272 | } 273 | } 274 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/NotFoundRequest.cs: -------------------------------------------------------------------------------- 1 | namespace NotFoundMiddlewareSample.Middleware 2 | { 3 | public class NotFoundRequest 4 | { 5 | public NotFoundRequest(string path) 6 | { 7 | // assumes case insensitive paths 8 | Path = path.ToLowerInvariant(); 9 | } 10 | 11 | public NotFoundRequest() 12 | { 13 | } 14 | public string Path { get; private set; } 15 | public int Count { get; private set; } 16 | public string CorrectedPath { get; private set; } 17 | 18 | public void IncrementCount() 19 | { 20 | Count++; 21 | } 22 | 23 | public void SetCorrectedPath(string path) 24 | { 25 | CorrectedPath = path; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Middleware/RequestTracker.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace NotFoundMiddlewareSample.Middleware 4 | { 5 | public class RequestTracker 6 | { 7 | private readonly INotFoundRequestRepository _repo; 8 | private static object _lock = new object(); 9 | 10 | public RequestTracker(INotFoundRequestRepository repo) 11 | { 12 | _repo = repo; 13 | } 14 | 15 | public void Record(string path) 16 | { 17 | string lowerPath = path.ToLowerInvariant(); 18 | lock (_lock) 19 | { 20 | var request = _repo.GetByPath(lowerPath); 21 | if (request != null) 22 | { 23 | request.IncrementCount(); 24 | } 25 | else 26 | { 27 | request = new NotFoundRequest(lowerPath); 28 | request.IncrementCount(); 29 | _repo.Add(request); 30 | } 31 | } 32 | } 33 | 34 | public IEnumerable ListRequests() 35 | { 36 | return _repo.List(); 37 | } 38 | 39 | public NotFoundRequest GetRequest(string path) 40 | { 41 | return _repo.GetByPath(path); 42 | } 43 | 44 | public void UpdateRequest(NotFoundRequest request) 45 | { 46 | _repo.Update(request); 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Migrations/00000000000000_CreateIdentitySchema.Designer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using NotFoundMiddlewareSample.Models; 7 | 8 | namespace NotFoundMiddlewareSample.Migrations 9 | { 10 | [DbContext(typeof(ApplicationDbContext))] 11 | [Migration("00000000000000_CreateIdentitySchema")] 12 | partial class CreateIdentitySchema 13 | { 14 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 15 | { 16 | modelBuilder 17 | .HasAnnotation("ProductVersion", "7.0.0-beta8") 18 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 19 | 20 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => 21 | { 22 | b.Property("Id"); 23 | 24 | b.Property("ConcurrencyStamp") 25 | .IsConcurrencyToken(); 26 | 27 | b.Property("Name") 28 | .HasAnnotation("MaxLength", 256); 29 | 30 | b.Property("NormalizedName") 31 | .HasAnnotation("MaxLength", 256); 32 | 33 | b.HasKey("Id"); 34 | 35 | b.HasIndex("NormalizedName") 36 | .HasAnnotation("Relational:Name", "RoleNameIndex"); 37 | 38 | b.HasAnnotation("Relational:TableName", "AspNetRoles"); 39 | }); 40 | 41 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim", b => 42 | { 43 | b.Property("Id") 44 | .ValueGeneratedOnAdd(); 45 | 46 | b.Property("ClaimType"); 47 | 48 | b.Property("ClaimValue"); 49 | 50 | b.Property("RoleId"); 51 | 52 | b.HasKey("Id"); 53 | 54 | b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); 55 | }); 56 | 57 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim", b => 58 | { 59 | b.Property("Id") 60 | .ValueGeneratedOnAdd(); 61 | 62 | b.Property("ClaimType"); 63 | 64 | b.Property("ClaimValue"); 65 | 66 | b.Property("UserId"); 67 | 68 | b.HasKey("Id"); 69 | 70 | b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); 71 | }); 72 | 73 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin", b => 74 | { 75 | b.Property("LoginProvider"); 76 | 77 | b.Property("ProviderKey"); 78 | 79 | b.Property("ProviderDisplayName"); 80 | 81 | b.Property("UserId"); 82 | 83 | b.HasKey("LoginProvider", "ProviderKey"); 84 | 85 | b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); 86 | }); 87 | 88 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole", b => 89 | { 90 | b.Property("UserId"); 91 | 92 | b.Property("RoleId"); 93 | 94 | b.HasKey("UserId", "RoleId"); 95 | 96 | b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); 97 | }); 98 | 99 | modelBuilder.Entity("NotFoundMiddlewareSample.Models.ApplicationUser", b => 100 | { 101 | b.Property("Id"); 102 | 103 | b.Property("AccessFailedCount"); 104 | 105 | b.Property("ConcurrencyStamp") 106 | .IsConcurrencyToken(); 107 | 108 | b.Property("Email") 109 | .HasAnnotation("MaxLength", 256); 110 | 111 | b.Property("EmailConfirmed"); 112 | 113 | b.Property("LockoutEnabled"); 114 | 115 | b.Property("LockoutEnd"); 116 | 117 | b.Property("NormalizedEmail") 118 | .HasAnnotation("MaxLength", 256); 119 | 120 | b.Property("NormalizedUserName") 121 | .HasAnnotation("MaxLength", 256); 122 | 123 | b.Property("PasswordHash"); 124 | 125 | b.Property("PhoneNumber"); 126 | 127 | b.Property("PhoneNumberConfirmed"); 128 | 129 | b.Property("SecurityStamp"); 130 | 131 | b.Property("TwoFactorEnabled"); 132 | 133 | b.Property("UserName") 134 | .HasAnnotation("MaxLength", 256); 135 | 136 | b.HasKey("Id"); 137 | 138 | b.HasIndex("NormalizedEmail") 139 | .HasAnnotation("Relational:Name", "EmailIndex"); 140 | 141 | b.HasIndex("NormalizedUserName") 142 | .HasAnnotation("Relational:Name", "UserNameIndex"); 143 | 144 | b.HasAnnotation("Relational:TableName", "AspNetUsers"); 145 | }); 146 | 147 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim", b => 148 | { 149 | b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") 150 | .WithMany() 151 | .HasForeignKey("RoleId"); 152 | }); 153 | 154 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim", b => 155 | { 156 | b.HasOne("NotFoundMiddlewareSample.Models.ApplicationUser") 157 | .WithMany() 158 | .HasForeignKey("UserId"); 159 | }); 160 | 161 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin", b => 162 | { 163 | b.HasOne("NotFoundMiddlewareSample.Models.ApplicationUser") 164 | .WithMany() 165 | .HasForeignKey("UserId"); 166 | }); 167 | 168 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole", b => 169 | { 170 | b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") 171 | .WithMany() 172 | .HasForeignKey("RoleId"); 173 | 174 | b.HasOne("NotFoundMiddlewareSample.Models.ApplicationUser") 175 | .WithMany() 176 | .HasForeignKey("UserId"); 177 | }); 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Migrations/00000000000000_CreateIdentitySchema.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Metadata; 3 | using Microsoft.EntityFrameworkCore.Migrations; 4 | 5 | namespace NotFoundMiddlewareSample.Migrations 6 | { 7 | public partial class CreateIdentitySchema : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.CreateTable( 12 | name: "AspNetRoles", 13 | columns: table => new 14 | { 15 | Id = table.Column(nullable: false), 16 | ConcurrencyStamp = table.Column(nullable: true), 17 | Name = table.Column(nullable: true), 18 | NormalizedName = table.Column(nullable: true) 19 | }, 20 | constraints: table => 21 | { 22 | table.PrimaryKey("PK_IdentityRole", x => x.Id); 23 | }); 24 | migrationBuilder.CreateTable( 25 | name: "AspNetUsers", 26 | columns: table => new 27 | { 28 | Id = table.Column(nullable: false), 29 | AccessFailedCount = table.Column(nullable: false), 30 | ConcurrencyStamp = table.Column(nullable: true), 31 | Email = table.Column(nullable: true), 32 | EmailConfirmed = table.Column(nullable: false), 33 | LockoutEnabled = table.Column(nullable: false), 34 | LockoutEnd = table.Column(nullable: true), 35 | NormalizedEmail = table.Column(nullable: true), 36 | NormalizedUserName = table.Column(nullable: true), 37 | PasswordHash = table.Column(nullable: true), 38 | PhoneNumber = table.Column(nullable: true), 39 | PhoneNumberConfirmed = table.Column(nullable: false), 40 | SecurityStamp = table.Column(nullable: true), 41 | TwoFactorEnabled = table.Column(nullable: false), 42 | UserName = table.Column(nullable: true) 43 | }, 44 | constraints: table => 45 | { 46 | table.PrimaryKey("PK_ApplicationUser", x => x.Id); 47 | }); 48 | migrationBuilder.CreateTable( 49 | name: "AspNetRoleClaims", 50 | columns: table => new 51 | { 52 | Id = table.Column(nullable: false) 53 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 54 | ClaimType = table.Column(nullable: true), 55 | ClaimValue = table.Column(nullable: true), 56 | RoleId = table.Column(nullable: true) 57 | }, 58 | constraints: table => 59 | { 60 | table.PrimaryKey("PK_IdentityRoleClaim", x => x.Id); 61 | table.ForeignKey( 62 | name: "FK_IdentityRoleClaim_IdentityRole_RoleId", 63 | column: x => x.RoleId, 64 | principalTable: "AspNetRoles", 65 | principalColumn: "Id"); 66 | }); 67 | migrationBuilder.CreateTable( 68 | name: "AspNetUserClaims", 69 | columns: table => new 70 | { 71 | Id = table.Column(nullable: false) 72 | .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), 73 | ClaimType = table.Column(nullable: true), 74 | ClaimValue = table.Column(nullable: true), 75 | UserId = table.Column(nullable: true) 76 | }, 77 | constraints: table => 78 | { 79 | table.PrimaryKey("PK_IdentityUserClaim", x => x.Id); 80 | table.ForeignKey( 81 | name: "FK_IdentityUserClaim_ApplicationUser_UserId", 82 | column: x => x.UserId, 83 | principalTable: "AspNetUsers", 84 | principalColumn: "Id"); 85 | }); 86 | migrationBuilder.CreateTable( 87 | name: "AspNetUserLogins", 88 | columns: table => new 89 | { 90 | LoginProvider = table.Column(nullable: false), 91 | ProviderKey = table.Column(nullable: false), 92 | ProviderDisplayName = table.Column(nullable: true), 93 | UserId = table.Column(nullable: true) 94 | }, 95 | constraints: table => 96 | { 97 | table.PrimaryKey("PK_IdentityUserLogin", x => new { x.LoginProvider, x.ProviderKey }); 98 | table.ForeignKey( 99 | name: "FK_IdentityUserLogin_ApplicationUser_UserId", 100 | column: x => x.UserId, 101 | principalTable: "AspNetUsers", 102 | principalColumn: "Id"); 103 | }); 104 | migrationBuilder.CreateTable( 105 | name: "AspNetUserRoles", 106 | columns: table => new 107 | { 108 | UserId = table.Column(nullable: false), 109 | RoleId = table.Column(nullable: false) 110 | }, 111 | constraints: table => 112 | { 113 | table.PrimaryKey("PK_IdentityUserRole", x => new { x.UserId, x.RoleId }); 114 | table.ForeignKey( 115 | name: "FK_IdentityUserRole_IdentityRole_RoleId", 116 | column: x => x.RoleId, 117 | principalTable: "AspNetRoles", 118 | principalColumn: "Id"); 119 | table.ForeignKey( 120 | name: "FK_IdentityUserRole_ApplicationUser_UserId", 121 | column: x => x.UserId, 122 | principalTable: "AspNetUsers", 123 | principalColumn: "Id"); 124 | }); 125 | migrationBuilder.CreateIndex( 126 | name: "RoleNameIndex", 127 | table: "AspNetRoles", 128 | column: "NormalizedName"); 129 | migrationBuilder.CreateIndex( 130 | name: "EmailIndex", 131 | table: "AspNetUsers", 132 | column: "NormalizedEmail"); 133 | migrationBuilder.CreateIndex( 134 | name: "UserNameIndex", 135 | table: "AspNetUsers", 136 | column: "NormalizedUserName"); 137 | } 138 | 139 | protected override void Down(MigrationBuilder migrationBuilder) 140 | { 141 | migrationBuilder.DropTable("AspNetRoleClaims"); 142 | migrationBuilder.DropTable("AspNetUserClaims"); 143 | migrationBuilder.DropTable("AspNetUserLogins"); 144 | migrationBuilder.DropTable("AspNetUserRoles"); 145 | migrationBuilder.DropTable("AspNetRoles"); 146 | migrationBuilder.DropTable("AspNetUsers"); 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Migrations/ApplicationDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Infrastructure; 4 | using Microsoft.EntityFrameworkCore.Metadata; 5 | using NotFoundMiddlewareSample.Models; 6 | 7 | namespace NotFoundMiddlewareSample.Migrations 8 | { 9 | [DbContext(typeof(ApplicationDbContext))] 10 | partial class ApplicationDbContextModelSnapshot : ModelSnapshot 11 | { 12 | protected override void BuildModel(ModelBuilder modelBuilder) 13 | { 14 | modelBuilder 15 | .HasAnnotation("ProductVersion", "7.0.0-beta8") 16 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 17 | 18 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => 19 | { 20 | b.Property("Id"); 21 | 22 | b.Property("ConcurrencyStamp") 23 | .IsConcurrencyToken(); 24 | 25 | b.Property("Name") 26 | .HasAnnotation("MaxLength", 256); 27 | 28 | b.Property("NormalizedName") 29 | .HasAnnotation("MaxLength", 256); 30 | 31 | b.HasKey("Id"); 32 | 33 | b.HasIndex("NormalizedName") 34 | .HasAnnotation("Relational:Name", "RoleNameIndex"); 35 | 36 | b.HasAnnotation("Relational:TableName", "AspNetRoles"); 37 | }); 38 | 39 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim", b => 40 | { 41 | b.Property("Id") 42 | .ValueGeneratedOnAdd(); 43 | 44 | b.Property("ClaimType"); 45 | 46 | b.Property("ClaimValue"); 47 | 48 | b.Property("RoleId"); 49 | 50 | b.HasKey("Id"); 51 | 52 | b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); 53 | }); 54 | 55 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim", b => 56 | { 57 | b.Property("Id") 58 | .ValueGeneratedOnAdd(); 59 | 60 | b.Property("ClaimType"); 61 | 62 | b.Property("ClaimValue"); 63 | 64 | b.Property("UserId"); 65 | 66 | b.HasKey("Id"); 67 | 68 | b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); 69 | }); 70 | 71 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin", b => 72 | { 73 | b.Property("LoginProvider"); 74 | 75 | b.Property("ProviderKey"); 76 | 77 | b.Property("ProviderDisplayName"); 78 | 79 | b.Property("UserId"); 80 | 81 | b.HasKey("LoginProvider", "ProviderKey"); 82 | 83 | b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); 84 | }); 85 | 86 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole", b => 87 | { 88 | b.Property("UserId"); 89 | 90 | b.Property("RoleId"); 91 | 92 | b.HasKey("UserId", "RoleId"); 93 | 94 | b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); 95 | }); 96 | 97 | modelBuilder.Entity("NotFoundMiddlewareSample.Models.ApplicationUser", b => 98 | { 99 | b.Property("Id"); 100 | 101 | b.Property("AccessFailedCount"); 102 | 103 | b.Property("ConcurrencyStamp") 104 | .IsConcurrencyToken(); 105 | 106 | b.Property("Email") 107 | .HasAnnotation("MaxLength", 256); 108 | 109 | b.Property("EmailConfirmed"); 110 | 111 | b.Property("LockoutEnabled"); 112 | 113 | b.Property("LockoutEnd"); 114 | 115 | b.Property("NormalizedEmail") 116 | .HasAnnotation("MaxLength", 256); 117 | 118 | b.Property("NormalizedUserName") 119 | .HasAnnotation("MaxLength", 256); 120 | 121 | b.Property("PasswordHash"); 122 | 123 | b.Property("PhoneNumber"); 124 | 125 | b.Property("PhoneNumberConfirmed"); 126 | 127 | b.Property("SecurityStamp"); 128 | 129 | b.Property("TwoFactorEnabled"); 130 | 131 | b.Property("UserName") 132 | .HasAnnotation("MaxLength", 256); 133 | 134 | b.HasKey("Id"); 135 | 136 | b.HasIndex("NormalizedEmail") 137 | .HasAnnotation("Relational:Name", "EmailIndex"); 138 | 139 | b.HasIndex("NormalizedUserName") 140 | .HasAnnotation("Relational:Name", "UserNameIndex"); 141 | 142 | b.HasAnnotation("Relational:TableName", "AspNetUsers"); 143 | }); 144 | 145 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim", b => 146 | { 147 | b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") 148 | .WithMany() 149 | .HasForeignKey("RoleId"); 150 | }); 151 | 152 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim", b => 153 | { 154 | b.HasOne("NotFoundMiddlewareSample.Models.ApplicationUser") 155 | .WithMany() 156 | .HasForeignKey("UserId"); 157 | }); 158 | 159 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin", b => 160 | { 161 | b.HasOne("NotFoundMiddlewareSample.Models.ApplicationUser") 162 | .WithMany() 163 | .HasForeignKey("UserId"); 164 | }); 165 | 166 | modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole", b => 167 | { 168 | b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") 169 | .WithMany() 170 | .HasForeignKey("RoleId"); 171 | 172 | b.HasOne("NotFoundMiddlewareSample.Models.ApplicationUser") 173 | .WithMany() 174 | .HasForeignKey("UserId"); 175 | }); 176 | } 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Migrations/NotFoundMiddlewareDb/20160421002656_NotFoundRequests.Designer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Infrastructure; 3 | using Microsoft.EntityFrameworkCore.Metadata; 4 | using Microsoft.EntityFrameworkCore.Migrations; 5 | using NotFoundMiddlewareSample.Middleware; 6 | 7 | namespace NotFoundMiddlewareSample.Migrations.NotFoundMiddlewareDb 8 | { 9 | [DbContext(typeof(NotFoundMiddlewareDbContext))] 10 | [Migration("20160421002656_NotFoundRequests")] 11 | partial class NotFoundRequests 12 | { 13 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 14 | { 15 | modelBuilder 16 | .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") 17 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 18 | 19 | modelBuilder.Entity("NotFoundMiddlewareSample.Middleware.NotFoundRequest", b => 20 | { 21 | b.Property("Path"); 22 | 23 | b.Property("CorrectedPath"); 24 | 25 | b.Property("Count"); 26 | 27 | b.HasKey("Path"); 28 | }); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Migrations/NotFoundMiddlewareDb/20160421002656_NotFoundRequests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | namespace NotFoundMiddlewareSample.Migrations.NotFoundMiddlewareDb 4 | { 5 | public partial class NotFoundRequests : Migration 6 | { 7 | protected override void Up(MigrationBuilder migrationBuilder) 8 | { 9 | migrationBuilder.CreateTable( 10 | name: "NotFoundRequest", 11 | columns: table => new 12 | { 13 | Path = table.Column(nullable: false), 14 | CorrectedPath = table.Column(nullable: true), 15 | Count = table.Column(nullable: false) 16 | }, 17 | constraints: table => 18 | { 19 | table.PrimaryKey("PK_NotFoundRequest", x => x.Path); 20 | }); 21 | } 22 | 23 | protected override void Down(MigrationBuilder migrationBuilder) 24 | { 25 | migrationBuilder.DropTable("NotFoundRequest"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Migrations/NotFoundMiddlewareDb/NotFoundMiddlewareDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Infrastructure; 3 | using Microsoft.EntityFrameworkCore.Metadata; 4 | using NotFoundMiddlewareSample.Middleware; 5 | 6 | namespace NotFoundMiddlewareSample.Migrations.NotFoundMiddlewareDb 7 | { 8 | [DbContext(typeof(NotFoundMiddlewareDbContext))] 9 | partial class NotFoundMiddlewareDbContextModelSnapshot : ModelSnapshot 10 | { 11 | protected override void BuildModel(ModelBuilder modelBuilder) 12 | { 13 | modelBuilder 14 | .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") 15 | .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); 16 | 17 | modelBuilder.Entity("NotFoundMiddlewareSample.Middleware.NotFoundRequest", b => 18 | { 19 | b.Property("Path"); 20 | 21 | b.Property("CorrectedPath"); 22 | 23 | b.Property("Count"); 24 | 25 | b.HasKey("Path"); 26 | }); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Models/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace NotFoundMiddlewareSample.Models 5 | { 6 | public class ApplicationDbContext : IdentityDbContext 7 | { 8 | public ApplicationDbContext(DbContextOptions options ) 9 | :base(options) 10 | { 11 | 12 | } 13 | protected override void OnModelCreating(ModelBuilder builder) 14 | { 15 | base.OnModelCreating(builder); 16 | // Customize the ASP.NET Identity model and override the defaults if needed. 17 | // For example, you can rename the ASP.NET Identity table names and more. 18 | // Add your customizations after calling base.OnModelCreating(builder); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Models/ApplicationUser.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 2 | 3 | namespace NotFoundMiddlewareSample.Models 4 | { 5 | // Add profile data for application users by adding properties to the ApplicationUser class 6 | public class ApplicationUser : IdentityUser 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/NotFoundMiddlewareSample.xproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 14.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | ca035d23-09ed-4080-8baa-fe8e4ca6caed 10 | NotFoundMiddlewareSample 11 | ..\..\artifacts\obj\$(MSBuildProjectName) 12 | .\bin\ 13 | 14 | 15 | 2.0 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Program.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using Microsoft.AspNetCore.Hosting; 3 | 4 | namespace NotFoundMiddlewareSample 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | var host = new WebHostBuilder() 11 | .UseKestrel() 12 | .UseContentRoot(Directory.GetCurrentDirectory()) 13 | .UseIISIntegration() 14 | .UseStartup() 15 | .Build(); 16 | 17 | host.Run(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:3241/", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "NotFoundMiddlewareSample": { 19 | "commandName": "Project", 20 | "launchBrowser": true, 21 | "launchUrl": "http://localhost:5000", 22 | "environmentVariables": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | } 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Services/IEmailSender.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace NotFoundMiddlewareSample.Services 7 | { 8 | public interface IEmailSender 9 | { 10 | Task SendEmailAsync(string email, string subject, string message); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Services/ISmsSender.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace NotFoundMiddlewareSample.Services 7 | { 8 | public interface ISmsSender 9 | { 10 | Task SendSmsAsync(string number, string message); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Services/MessageServices.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace NotFoundMiddlewareSample.Services 7 | { 8 | // This class is used by the application to send Email and SMS 9 | // when you turn on two-factor authentication in ASP.NET Identity. 10 | // For more details see this link http://go.microsoft.com/fwlink/?LinkID=532713 11 | public class AuthMessageSender : IEmailSender, ISmsSender 12 | { 13 | public Task SendEmailAsync(string email, string subject, string message) 14 | { 15 | // Plug in your email service here to send an email. 16 | return Task.FromResult(0); 17 | } 18 | 19 | public Task SendSmsAsync(string number, string message) 20 | { 21 | // Plug in your SMS service here to send a text message. 22 | return Task.FromResult(0); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Logging; 8 | using NotFoundMiddlewareSample.Middleware; 9 | using NotFoundMiddlewareSample.Models; 10 | using NotFoundMiddlewareSample.Services; 11 | 12 | namespace NotFoundMiddlewareSample 13 | { 14 | public class Startup 15 | { 16 | public Startup(IHostingEnvironment env) 17 | { 18 | // Set up configuration sources. 19 | 20 | var builder = new ConfigurationBuilder() 21 | .SetBasePath(env.ContentRootPath) 22 | .AddJsonFile("appsettings.json") 23 | .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); 24 | 25 | builder.AddEnvironmentVariables(); 26 | Configuration = builder.Build(); 27 | } 28 | 29 | public IConfigurationRoot Configuration { get; set; } 30 | 31 | // This method gets called by the runtime. Use this method to add services to the container. 32 | public void ConfigureServices(IServiceCollection services) 33 | { 34 | #region Application-Specific Stuff 35 | // Add Application Services 36 | services.AddDbContext(options => 37 | options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 38 | 39 | services.AddIdentity() 40 | .AddEntityFrameworkStores() 41 | .AddDefaultTokenProviders(); 42 | 43 | services.AddMvc(); 44 | #endregion 45 | 46 | // Configure NotFound Middleware Services (last one wins if multiple) 47 | services.AddNotFoundMiddlewareInMemory(); 48 | //services.AddNotFoundMiddlewareEntityFramework(Configuration.GetConnectionString("DefaultConnection")); 49 | 50 | // Add NotFound Middleware Config Options 51 | services.Configure(Configuration.GetSection("NotFoundMiddleware")); 52 | 53 | #region Add other application services 54 | // Add application services. 55 | services.AddTransient(); 56 | services.AddScoped(); 57 | services.AddSingleton(); 58 | #endregion 59 | } 60 | 61 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 62 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 63 | { 64 | loggerFactory.AddConsole(Configuration.GetSection("Logging")); 65 | loggerFactory.AddDebug(); 66 | 67 | app.UseNotFoundPageMiddleware(); 68 | 69 | app.UseNotFoundMiddleware(); 70 | 71 | if (env.IsDevelopment()) 72 | { 73 | //app.UseBrowserLink(); 74 | app.UseDeveloperExceptionPage(); 75 | app.UseDatabaseErrorPage(); 76 | } 77 | else 78 | { 79 | app.UseExceptionHandler("/Home/Error"); 80 | } 81 | 82 | app.UseStaticFiles(); 83 | 84 | app.UseStatusCodePages(); 85 | 86 | app.UseIdentity(); 87 | 88 | app.UseMvc(routes => 89 | { 90 | routes.MapRoute( 91 | name: "default", 92 | template: "{controller=Home}/{action=Index}/{id?}"); 93 | }); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Account/ExternalLoginConfirmationViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Account 4 | { 5 | public class ExternalLoginConfirmationViewModel 6 | { 7 | [Required] 8 | [EmailAddress] 9 | public string Email { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Account/ForgotPasswordViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Account 4 | { 5 | public class ForgotPasswordViewModel 6 | { 7 | [Required] 8 | [EmailAddress] 9 | public string Email { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Account/LoginViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Account 4 | { 5 | public class LoginViewModel 6 | { 7 | [Required] 8 | [EmailAddress] 9 | public string Email { get; set; } 10 | 11 | [Required] 12 | [DataType(DataType.Password)] 13 | public string Password { get; set; } 14 | 15 | [Display(Name = "Remember me?")] 16 | public bool RememberMe { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Account/RegisterViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Account 4 | { 5 | public class RegisterViewModel 6 | { 7 | [Required] 8 | [EmailAddress] 9 | [Display(Name = "Email")] 10 | public string Email { get; set; } 11 | 12 | [Required] 13 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 14 | [DataType(DataType.Password)] 15 | [Display(Name = "Password")] 16 | public string Password { get; set; } 17 | 18 | [DataType(DataType.Password)] 19 | [Display(Name = "Confirm password")] 20 | [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 21 | public string ConfirmPassword { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Account/ResetPasswordViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Account 4 | { 5 | public class ResetPasswordViewModel 6 | { 7 | [Required] 8 | [EmailAddress] 9 | public string Email { get; set; } 10 | 11 | [Required] 12 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 13 | [DataType(DataType.Password)] 14 | public string Password { get; set; } 15 | 16 | [DataType(DataType.Password)] 17 | [Display(Name = "Confirm password")] 18 | [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 19 | public string ConfirmPassword { get; set; } 20 | 21 | public string Code { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Account/SendCodeViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.AspNetCore.Mvc.Rendering; 3 | 4 | namespace NotFoundMiddlewareSample.ViewModels.Account 5 | { 6 | public class SendCodeViewModel 7 | { 8 | public string SelectedProvider { get; set; } 9 | 10 | public ICollection Providers { get; set; } 11 | 12 | public string ReturnUrl { get; set; } 13 | 14 | public bool RememberMe { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Account/VerifyCodeViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Account 4 | { 5 | public class VerifyCodeViewModel 6 | { 7 | [Required] 8 | public string Provider { get; set; } 9 | 10 | [Required] 11 | public string Code { get; set; } 12 | 13 | public string ReturnUrl { get; set; } 14 | 15 | [Display(Name = "Remember this browser?")] 16 | public bool RememberBrowser { get; set; } 17 | 18 | [Display(Name = "Remember me?")] 19 | public bool RememberMe { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Manage/AddPhoneNumberViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Manage 4 | { 5 | public class AddPhoneNumberViewModel 6 | { 7 | [Required] 8 | [Phone] 9 | [Display(Name = "Phone number")] 10 | public string PhoneNumber { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Manage/ChangePasswordViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Manage 4 | { 5 | public class ChangePasswordViewModel 6 | { 7 | [Required] 8 | [DataType(DataType.Password)] 9 | [Display(Name = "Current password")] 10 | public string OldPassword { get; set; } 11 | 12 | [Required] 13 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 14 | [DataType(DataType.Password)] 15 | [Display(Name = "New password")] 16 | public string NewPassword { get; set; } 17 | 18 | [DataType(DataType.Password)] 19 | [Display(Name = "Confirm new password")] 20 | [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] 21 | public string ConfirmPassword { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Manage/ConfigureTwoFactorViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.AspNetCore.Mvc.Rendering; 3 | 4 | namespace NotFoundMiddlewareSample.ViewModels.Manage 5 | { 6 | public class ConfigureTwoFactorViewModel 7 | { 8 | public string SelectedProvider { get; set; } 9 | 10 | public ICollection Providers { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Manage/FactorViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace NotFoundMiddlewareSample.ViewModels.Manage 2 | { 3 | public class FactorViewModel 4 | { 5 | public string Purpose { get; set; } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Manage/IndexViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.AspNetCore.Identity; 3 | 4 | namespace NotFoundMiddlewareSample.ViewModels.Manage 5 | { 6 | public class IndexViewModel 7 | { 8 | public bool HasPassword { get; set; } 9 | 10 | public IList Logins { get; set; } 11 | 12 | public string PhoneNumber { get; set; } 13 | 14 | public bool TwoFactor { get; set; } 15 | 16 | public bool BrowserRemembered { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Manage/ManageLoginsViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.AspNetCore.Http.Authentication; 3 | using Microsoft.AspNetCore.Identity; 4 | 5 | namespace NotFoundMiddlewareSample.ViewModels.Manage 6 | { 7 | public class ManageLoginsViewModel 8 | { 9 | public IList CurrentLogins { get; set; } 10 | 11 | public IList OtherLogins { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Manage/RemoveLoginViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace NotFoundMiddlewareSample.ViewModels.Manage 2 | { 3 | public class RemoveLoginViewModel 4 | { 5 | public string LoginProvider { get; set; } 6 | public string ProviderKey { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Manage/SetPasswordViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Manage 4 | { 5 | public class SetPasswordViewModel 6 | { 7 | [Required] 8 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 9 | [DataType(DataType.Password)] 10 | [Display(Name = "New password")] 11 | public string NewPassword { get; set; } 12 | 13 | [DataType(DataType.Password)] 14 | [Display(Name = "Confirm new password")] 15 | [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] 16 | public string ConfirmPassword { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/ViewModels/Manage/VerifyPhoneNumberViewModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace NotFoundMiddlewareSample.ViewModels.Manage 4 | { 5 | public class VerifyPhoneNumberViewModel 6 | { 7 | [Required] 8 | public string Code { get; set; } 9 | 10 | [Required] 11 | [Phone] 12 | [Display(Name = "Phone number")] 13 | public string PhoneNumber { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/ConfirmEmail.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Confirm Email"; 3 | } 4 | 5 |

@ViewData["Title"].

6 |
7 |

8 | Thank you for confirming your email. Please Click here to Log in. 9 |

10 |
11 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/ExternalLoginConfirmation.cshtml: -------------------------------------------------------------------------------- 1 | @model ExternalLoginConfirmationViewModel 2 | @{ 3 | ViewData["Title"] = "Register"; 4 | } 5 | 6 |

@ViewData["Title"].

7 |

Associate your @ViewData["LoginProvider"] account.

8 | 9 |
10 |

Association Form

11 |
12 |
13 | 14 |

15 | You've successfully authenticated with @ViewData["LoginProvider"]. 16 | Please enter a user name for this site below and click the Register button to finish 17 | logging in. 18 |

19 |
20 | 21 |
22 | 23 | 24 |
25 |
26 |
27 |
28 | 29 |
30 |
31 |
32 | 33 | @section Scripts { 34 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 35 | } 36 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/ExternalLoginFailure.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Login Failure"; 3 | } 4 | 5 |
6 |

@ViewData["Title"].

7 |

Unsuccessful login with service.

8 |
9 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/ForgotPassword.cshtml: -------------------------------------------------------------------------------- 1 | @model ForgotPasswordViewModel 2 | @{ 3 | ViewData["Title"] = "Forgot your password?"; 4 | } 5 | 6 |

@ViewData["Title"].

7 |

8 | For more information on how to enable reset password please see this article. 9 |

10 | 11 | @*
12 |

Enter your email.

13 |
14 |
15 |
16 | 17 |
18 | 19 | 20 |
21 |
22 |
23 |
24 | 25 |
26 |
27 |
*@ 28 | 29 | @section Scripts { 30 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 31 | } 32 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/ForgotPasswordConfirmation.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Forgot Password Confirmation"; 3 | } 4 | 5 |

@ViewData["Title"].

6 |

7 | Please check your email to reset your password. 8 |

9 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/Lockout.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Locked out"; 3 | } 4 | 5 |
6 |

Locked out.

7 |

This account has been locked out, please try again later.

8 |
9 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/Login.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Collections.Generic 2 | @using Microsoft.AspNet.Http 3 | @using Microsoft.AspNet.Http.Authentication 4 | @model LoginViewModel 5 | @inject SignInManager SignInManager 6 | 7 | @{ 8 | ViewData["Title"] = "Log in"; 9 | } 10 | 11 |

@ViewData["Title"].

12 |
13 |
14 |
15 |
16 |

Use a local account to log in.

17 |
18 |
19 |
20 | 21 |
22 | 23 | 24 |
25 |
26 |
27 | 28 |
29 | 30 | 31 |
32 |
33 |
34 |
35 |
36 | 37 | 38 |
39 |
40 |
41 |
42 |
43 | 44 |
45 |
46 |

47 | Register as a new user? 48 |

49 |

50 | Forgot your password? 51 |

52 |
53 |
54 |
55 |
56 |
57 |

Use another service to log in.

58 |
59 | @{ 60 | var loginProviders = SignInManager.GetExternalAuthenticationSchemes().ToList(); 61 | if (loginProviders.Count == 0) 62 | { 63 |
64 |

65 | There are no external authentication services configured. See this article 66 | for details on setting up this ASP.NET application to support logging in via external services. 67 |

68 |
69 | } 70 | else 71 | { 72 |
73 |
74 |

75 | @foreach (var provider in loginProviders) 76 | { 77 | 78 | } 79 |

80 |
81 |
82 | } 83 | } 84 |
85 |
86 |
87 | 88 | @section Scripts { 89 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 90 | } 91 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/Register.cshtml: -------------------------------------------------------------------------------- 1 | @model RegisterViewModel 2 | @{ 3 | ViewData["Title"] = "Register"; 4 | } 5 | 6 |

@ViewData["Title"].

7 | 8 |
9 |

Create a new account.

10 |
11 |
12 |
13 | 14 |
15 | 16 | 17 |
18 |
19 |
20 | 21 |
22 | 23 | 24 |
25 |
26 |
27 | 28 |
29 | 30 | 31 |
32 |
33 |
34 |
35 | 36 |
37 |
38 |
39 | 40 | @section Scripts { 41 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 42 | } 43 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/ResetPassword.cshtml: -------------------------------------------------------------------------------- 1 | @model ResetPasswordViewModel 2 | @{ 3 | ViewData["Title"] = "Reset password"; 4 | } 5 | 6 |

@ViewData["Title"].

7 | 8 |
9 |

Reset your password.

10 |
11 |
12 | 13 |
14 | 15 |
16 | 17 | 18 |
19 |
20 |
21 | 22 |
23 | 24 | 25 |
26 |
27 |
28 | 29 |
30 | 31 | 32 |
33 |
34 |
35 |
36 | 37 |
38 |
39 |
40 | 41 | @section Scripts { 42 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 43 | } 44 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/ResetPasswordConfirmation.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Reset password confirmation"; 3 | } 4 | 5 |

@ViewData["Title"].

6 |

7 | Your password has been reset. Please Click here to log in. 8 |

9 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/SendCode.cshtml: -------------------------------------------------------------------------------- 1 | @model SendCodeViewModel 2 | @{ 3 | ViewData["Title"] = "Send Verification Code"; 4 | } 5 | 6 |

@ViewData["Title"].

7 | 8 |
9 | 10 |
11 |
12 | Select Two-Factor Authentication Provider: 13 | 14 | 15 |
16 |
17 |
18 | 19 | @section Scripts { 20 | @{await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 21 | } 22 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Account/VerifyCode.cshtml: -------------------------------------------------------------------------------- 1 | @model VerifyCodeViewModel 2 | @{ 3 | ViewData["Title"] = "Verify"; 4 | } 5 | 6 |

@ViewData["Title"].

7 | 8 |
9 |
10 | 11 | 12 |

@ViewData["Status"]

13 |
14 |
15 | 16 |
17 | 18 | 19 |
20 |
21 |
22 |
23 |
24 | 25 | 26 |
27 |
28 |
29 |
30 |
31 | 32 |
33 |
34 |
35 | 36 | @section Scripts { 37 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 38 | } 39 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Home/About.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "About"; 3 | } 4 |

@ViewData["Title"].

5 |

@ViewData["Message"]

6 | 7 |

Use this area to provide additional information.

8 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Home/Contact.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Contact"; 3 | } 4 |

@ViewData["Title"].

5 |

@ViewData["Message"]

6 | 7 |
8 | One Microsoft Way
9 | Redmond, WA 98052-6399
10 | P: 11 | 425.555.0100 12 |
13 | 14 |
15 | Support: Support@example.com
16 | Marketing: Marketing@example.com 17 |
18 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Home/Index.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Home Page"; 3 | } 4 | 5 |
6 |
7 |

404 Middleware Sample

8 | 13 |
14 |
15 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Manage/AddPhoneNumber.cshtml: -------------------------------------------------------------------------------- 1 | @model AddPhoneNumberViewModel 2 | @{ 3 | ViewData["Title"] = "Add Phone Number"; 4 | } 5 | 6 |

@ViewData["Title"].

7 |
8 |

Add a phone number.

9 |
10 |
11 |
12 | 13 |
14 | 15 | 16 |
17 |
18 |
19 |
20 | 21 |
22 |
23 |
24 | 25 | @section Scripts { 26 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 27 | } 28 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Manage/ChangePassword.cshtml: -------------------------------------------------------------------------------- 1 | @model ChangePasswordViewModel 2 | @{ 3 | ViewData["Title"] = "Change Password"; 4 | } 5 | 6 |

@ViewData["Title"].

7 | 8 |
9 |

Change Password Form

10 |
11 |
12 |
13 | 14 |
15 | 16 | 17 |
18 |
19 |
20 | 21 |
22 | 23 | 24 |
25 |
26 |
27 | 28 |
29 | 30 | 31 |
32 |
33 |
34 |
35 | 36 |
37 |
38 |
39 | 40 | @section Scripts { 41 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 42 | } 43 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Manage/Index.cshtml: -------------------------------------------------------------------------------- 1 | @model IndexViewModel 2 | @{ 3 | ViewData["Title"] = "Manage your account"; 4 | } 5 | 6 |

@ViewData["Title"].

7 |

@ViewData["StatusMessage"]

8 |
9 |

Change your account settings

10 |
11 |
12 |
Password:
13 |
14 | [ 15 | @if (Model.HasPassword) 16 | { 17 | Change 18 | } 19 | else 20 | { 21 | Create 22 | } 23 | ] 24 |
25 |
External Logins:
26 |
27 | 28 | @Model.Logins.Count [Manage] 29 |
30 | 31 | 32 |
Phone Number:
33 |
34 |

35 | Phone Numbers can used as a second factor of verification in two-factor authentication. 36 | See this article 37 | for details on setting up this ASP.NET application to support two-factor authentication using SMS. 38 |

39 | @*@(Model.PhoneNumber ?? "None") [ 40 | @if (Model.PhoneNumber != null) 41 | { 42 | Change 43 | @:  |  44 | Remove 45 | } 46 | else 47 | { 48 | Add 49 | } 50 | ]*@ 51 |
52 | 53 |
Two-Factor Authentication:
54 |
55 |

56 | There are no two-factor authentication providers configured. See this article 57 | for setting up this application to support two-factor authentication. 58 |

59 | @*@if (Model.TwoFactor) 60 | { 61 |
62 | 63 | Enabled 64 | 65 | 66 |
67 | } 68 | else 69 | { 70 |
71 | 72 | Disabled 73 | 74 | 75 |
76 | }*@ 77 |
78 |
79 |
80 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Manage/ManageLogins.cshtml: -------------------------------------------------------------------------------- 1 | @model ManageLoginsViewModel 2 | @using Microsoft.AspNet.Http.Authentication 3 | @{ 4 | ViewData["Title"] = "Manage your external logins"; 5 | } 6 | 7 |

@ViewData["Title"].

8 | 9 |

@ViewData["StatusMessage"]

10 | @if (Model.CurrentLogins.Count > 0) 11 | { 12 |

Registered Logins

13 | 14 | 15 | @foreach (var account in Model.CurrentLogins) 16 | { 17 | 18 | 19 | 35 | 36 | } 37 | 38 |
@account.LoginProvider 20 | @if ((bool)ViewData["ShowRemoveButton"]) 21 | { 22 |
23 |
24 | 25 | 26 | 27 |
28 |
29 | } 30 | else 31 | { 32 | @:   33 | } 34 |
39 | } 40 | @if (Model.OtherLogins.Count > 0) 41 | { 42 |

Add another service to log in.

43 |
44 |
45 |
46 |

47 | @foreach (var provider in Model.OtherLogins) 48 | { 49 | 50 | } 51 |

52 |
53 |
54 | } 55 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Manage/SetPassword.cshtml: -------------------------------------------------------------------------------- 1 | @model SetPasswordViewModel 2 | @{ 3 | ViewData["Title"] = "Set Password"; 4 | } 5 | 6 |

7 | You do not have a local username/password for this site. Add a local 8 | account so you can log in without an external login. 9 |

10 | 11 |
12 |

Set your password

13 |
14 |
15 |
16 | 17 |
18 | 19 | 20 |
21 |
22 |
23 | 24 |
25 | 26 | 27 |
28 |
29 |
30 |
31 | 32 |
33 |
34 |
35 | 36 | @section Scripts { 37 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 38 | } 39 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Manage/VerifyPhoneNumber.cshtml: -------------------------------------------------------------------------------- 1 | @model VerifyPhoneNumberViewModel 2 | @{ 3 | ViewData["Title"] = "Verify Phone Number"; 4 | } 5 | 6 |

@ViewData["Title"].

7 | 8 |
9 | 10 |

Add a phone number.

11 |
@ViewData["Status"]
12 |
13 |
14 |
15 | 16 |
17 | 18 | 19 |
20 |
21 |
22 |
23 | 24 |
25 |
26 |
27 | 28 | @section Scripts { 29 | @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } 30 | } 31 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Error"; 3 | } 4 | 5 |

Error.

6 |

An error occurred while processing your request.

7 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | @ViewData["Title"] - NotFoundMiddlewareSample 7 | 8 | 9 | 10 | 11 | 12 | 13 | 16 | 17 | 18 | 19 | 20 | 41 |
42 | @RenderBody() 43 |
44 |
45 |

© 2016 - NotFoundMiddlewareSample

46 |
47 |
48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 59 | 63 | 64 | 65 | 66 | @RenderSection("scripts", required: false) 67 | 68 | 69 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Shared/_LoginPartial.cshtml: -------------------------------------------------------------------------------- 1 | @using Microsoft.AspNetCore.Identity 2 | @using NotFoundMiddlewareSample.Models 3 | 4 | @inject SignInManager SignInManager 5 | @inject UserManager UserManager 6 | 7 | @if (SignInManager.IsSignedIn(User)) 8 | { 9 | 19 | } 20 | else 21 | { 22 | 26 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/Shared/_ValidationScriptsPartial.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 10 | 14 | 15 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @using NotFoundMiddlewareSample 2 | @using NotFoundMiddlewareSample.Models 3 | @using NotFoundMiddlewareSample.ViewModels.Account 4 | @using NotFoundMiddlewareSample.ViewModels.Manage 5 | @using Microsoft.AspNetCore.Identity 6 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 7 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "_Layout"; 3 | } 4 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-NotFoundMiddlewareSample-02f48966-435c-411d-b088-ecc93d269007;Trusted_Connection=True;MultipleActiveResultSets=true" 4 | }, 5 | "Logging": { 6 | "IncludeScopes": false, 7 | "LogLevel": { 8 | "Default": "Trace", 9 | "System": "Information", 10 | "Microsoft": "Information" 11 | } 12 | }, 13 | "NotFoundMiddleware": { 14 | "Path": "/fixbadlinks", 15 | "FixPathBehavior": "Redirect" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ASP.NET", 3 | "private": true, 4 | "dependencies": { 5 | "bootstrap": "3.3.5", 6 | "jquery": "2.1.4", 7 | "jquery-validation": "1.14.0", 8 | "jquery-validation-unobtrusive": "3.2.4" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/gulpfile.js: -------------------------------------------------------------------------------- 1 | /// 2 | "use strict"; 3 | 4 | var gulp = require("gulp"), 5 | rimraf = require("rimraf"), 6 | concat = require("gulp-concat"), 7 | cssmin = require("gulp-cssmin"), 8 | uglify = require("gulp-uglify"); 9 | 10 | var paths = { 11 | webroot: "./wwwroot/" 12 | }; 13 | 14 | paths.js = paths.webroot + "js/**/*.js"; 15 | paths.minJs = paths.webroot + "js/**/*.min.js"; 16 | paths.css = paths.webroot + "css/**/*.css"; 17 | paths.minCss = paths.webroot + "css/**/*.min.css"; 18 | paths.concatJsDest = paths.webroot + "js/site.min.js"; 19 | paths.concatCssDest = paths.webroot + "css/site.min.css"; 20 | 21 | gulp.task("clean:js", function (cb) { 22 | rimraf(paths.concatJsDest, cb); 23 | }); 24 | 25 | gulp.task("clean:css", function (cb) { 26 | rimraf(paths.concatCssDest, cb); 27 | }); 28 | 29 | gulp.task("clean", ["clean:js", "clean:css"]); 30 | 31 | gulp.task("min:js", function () { 32 | return gulp.src([paths.js, "!" + paths.minJs], { base: "." }) 33 | .pipe(concat(paths.concatJsDest)) 34 | .pipe(uglify()) 35 | .pipe(gulp.dest(".")); 36 | }); 37 | 38 | gulp.task("min:css", function () { 39 | return gulp.src([paths.css, "!" + paths.minCss]) 40 | .pipe(concat(paths.concatCssDest)) 41 | .pipe(cssmin()) 42 | .pipe(gulp.dest(".")); 43 | }); 44 | 45 | gulp.task("min", ["min:js", "min:css"]); 46 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ASP.NET", 3 | "version": "0.0.0", 4 | "devDependencies": { 5 | "gulp": "3.8.11", 6 | "gulp-concat": "2.5.2", 7 | "gulp-cssmin": "0.1.7", 8 | "gulp-uglify": "1.2.0", 9 | "rimraf": "2.2.8" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0-*", 3 | 4 | "dependencies": { 5 | "Microsoft.NETCore.App": { 6 | "version": "1.0.0", 7 | "type": "platform" 8 | }, 9 | "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0", 10 | "Microsoft.AspNetCore.Diagnostics": "1.0.0", 11 | "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0", 12 | "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0", 13 | "Microsoft.AspNetCore.Mvc": "1.0.0", 14 | "Microsoft.AspNetCore.Razor.Tools": { 15 | "version": "1.0.0-preview2-final", 16 | "type": "build" 17 | }, 18 | "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", 19 | "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", 20 | "Microsoft.AspNetCore.StaticFiles": "1.0.0", 21 | "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0", 22 | "Microsoft.EntityFrameworkCore.Tools": { 23 | "version": "1.0.0-preview2-final", 24 | "type": "build" 25 | }, 26 | "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", 27 | "Microsoft.Extensions.Configuration.Json": "1.0.0", 28 | "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0", 29 | "Microsoft.Extensions.Logging": "1.0.0", 30 | "Microsoft.Extensions.Logging.Console": "1.0.0", 31 | "Microsoft.Extensions.Logging.Debug": "1.0.0", 32 | "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", 33 | "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0" 34 | }, 35 | 36 | "tools": { 37 | "BundlerMinifier.Core": "2.0.238", 38 | "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final", 39 | "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final" 40 | }, 41 | 42 | "frameworks": { 43 | "netcoreapp1.0": { 44 | "imports": [ 45 | "dotnet5.6", 46 | "dnxcore50", 47 | "portable-net45+win8" 48 | ] 49 | } 50 | }, 51 | 52 | "buildOptions": { 53 | "emitEntryPoint": true, 54 | "preserveCompilationContext": true 55 | }, 56 | 57 | "runtimeOptions": { 58 | "configProperties": { 59 | "System.GC.Server": true 60 | } 61 | }, 62 | 63 | "publishOptions": { 64 | "include": [ 65 | "wwwroot", 66 | "Views", 67 | "appsettings.json", 68 | "web.config" 69 | ] 70 | }, 71 | 72 | "scripts": { 73 | "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ], 74 | "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] 75 | }} 76 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/FixedLink.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | Fixed Link 4 | 5 | 6 |

There I Fixed It

7 |

This is a static HTML page you can send "fixed" links to if you want.

8 | 9 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/_references.js: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | /// 5 | /// 6 | /// 7 | /// 8 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/css/site.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | padding-bottom: 20px; 4 | } 5 | 6 | /* Wrapping element */ 7 | /* Set some basic padding to keep content from hitting the edges */ 8 | .body-content { 9 | padding-left: 15px; 10 | padding-right: 15px; 11 | } 12 | 13 | /* Set widths on the form inputs since otherwise they're 100% wide */ 14 | input, 15 | select, 16 | textarea { 17 | max-width: 280px; 18 | } 19 | 20 | /* Carousel */ 21 | .carousel-caption { 22 | z-index: 10 !important; 23 | } 24 | 25 | .carousel-caption p { 26 | font-size: 20px; 27 | line-height: 1.4; 28 | } 29 | 30 | @media (min-width: 768px) { 31 | .carousel-caption { 32 | z-index: 10 !important; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/NotFoundMiddlewareSample/487747548bd9ba28466849e7b126e1f022def91c/src/NotFoundMiddlewareSample/wwwroot/favicon.ico -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/images/ASP-NET-Banners-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/NotFoundMiddlewareSample/487747548bd9ba28466849e7b126e1f022def91c/src/NotFoundMiddlewareSample/wwwroot/images/ASP-NET-Banners-01.png -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/images/ASP-NET-Banners-02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/NotFoundMiddlewareSample/487747548bd9ba28466849e7b126e1f022def91c/src/NotFoundMiddlewareSample/wwwroot/images/ASP-NET-Banners-02.png -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/images/Banner-01-Azure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/NotFoundMiddlewareSample/487747548bd9ba28466849e7b126e1f022def91c/src/NotFoundMiddlewareSample/wwwroot/images/Banner-01-Azure.png -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/images/Banner-02-VS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/NotFoundMiddlewareSample/487747548bd9ba28466849e7b126e1f022def91c/src/NotFoundMiddlewareSample/wwwroot/images/Banner-02-VS.png -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/js/site.js: -------------------------------------------------------------------------------- 1 | // Write your Javascript code. 2 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/.bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bootstrap", 3 | "description": "The most popular front-end framework for developing responsive, mobile first projects on the web.", 4 | "keywords": [ 5 | "css", 6 | "js", 7 | "less", 8 | "mobile-first", 9 | "responsive", 10 | "front-end", 11 | "framework", 12 | "web" 13 | ], 14 | "homepage": "http://getbootstrap.com", 15 | "license": "MIT", 16 | "moduleType": "globals", 17 | "main": [ 18 | "less/bootstrap.less", 19 | "dist/js/bootstrap.js" 20 | ], 21 | "ignore": [ 22 | "/.*", 23 | "_config.yml", 24 | "CNAME", 25 | "composer.json", 26 | "CONTRIBUTING.md", 27 | "docs", 28 | "js/tests", 29 | "test-infra" 30 | ], 31 | "dependencies": { 32 | "jquery": ">= 1.9.1" 33 | }, 34 | "version": "3.3.5", 35 | "_release": "3.3.5", 36 | "_resolution": { 37 | "type": "version", 38 | "tag": "v3.3.5", 39 | "commit": "16b48259a62f576e52c903c476bd42b90ab22482" 40 | }, 41 | "_source": "git://github.com/twbs/bootstrap.git", 42 | "_target": "3.3.5", 43 | "_originalSource": "bootstrap" 44 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2011-2015 Twitter, Inc 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/NotFoundMiddlewareSample/487747548bd9ba28466849e7b126e1f022def91c/src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/NotFoundMiddlewareSample/487747548bd9ba28466849e7b126e1f022def91c/src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/NotFoundMiddlewareSample/487747548bd9ba28466849e7b126e1f022def91c/src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/NotFoundMiddlewareSample/487747548bd9ba28466849e7b126e1f022def91c/src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/bootstrap/dist/js/npm.js: -------------------------------------------------------------------------------- 1 | // This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment. 2 | require('../../js/transition.js') 3 | require('../../js/alert.js') 4 | require('../../js/button.js') 5 | require('../../js/carousel.js') 6 | require('../../js/collapse.js') 7 | require('../../js/dropdown.js') 8 | require('../../js/modal.js') 9 | require('../../js/tooltip.js') 10 | require('../../js/popover.js') 11 | require('../../js/scrollspy.js') 12 | require('../../js/tab.js') 13 | require('../../js/affix.js') -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/jquery-validation-unobtrusive/.bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jquery-validation-unobtrusive", 3 | "version": "3.2.4", 4 | "homepage": "https://github.com/aspnet/jquery-validation-unobtrusive", 5 | "description": "Add-on to jQuery Validation to enable unobtrusive validation options in data-* attributes.", 6 | "main": [ 7 | "jquery.validate.unobtrusive.js" 8 | ], 9 | "ignore": [ 10 | "**/.*", 11 | "*.json", 12 | "*.md", 13 | "*.txt", 14 | "gulpfile.js" 15 | ], 16 | "keywords": [ 17 | "jquery", 18 | "asp.net", 19 | "mvc", 20 | "validation", 21 | "unobtrusive" 22 | ], 23 | "authors": [ 24 | "Microsoft" 25 | ], 26 | "license": "http://www.microsoft.com/web/webpi/eula/net_library_eula_enu.htm", 27 | "repository": { 28 | "type": "git", 29 | "url": "git://github.com/aspnet/jquery-validation-unobtrusive.git" 30 | }, 31 | "dependencies": { 32 | "jquery-validation": ">=1.8", 33 | "jquery": ">=1.8" 34 | }, 35 | "_release": "3.2.4", 36 | "_resolution": { 37 | "type": "version", 38 | "tag": "v3.2.4", 39 | "commit": "13386cd1b5947d8a5d23a12b531ce3960be1eba7" 40 | }, 41 | "_source": "git://github.com/aspnet/jquery-validation-unobtrusive.git", 42 | "_target": "3.2.4", 43 | "_originalSource": "jquery-validation-unobtrusive" 44 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js: -------------------------------------------------------------------------------- 1 | /* 2 | ** Unobtrusive validation support library for jQuery and jQuery Validate 3 | ** Copyright (C) Microsoft Corporation. All rights reserved. 4 | */ 5 | !function(a){function e(a,e,n){a.rules[e]=n,a.message&&(a.messages[e]=a.message)}function n(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function t(a){return a.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function r(a){return a.substr(0,a.lastIndexOf(".")+1)}function i(a,e){return 0===a.indexOf("*.")&&(a=a.replace("*.",e)),a}function o(e,n){var r=a(this).find("[data-valmsg-for='"+t(n[0].name)+"']"),i=r.attr("data-valmsg-replace"),o=i?a.parseJSON(i)!==!1:null;r.removeClass("field-validation-valid").addClass("field-validation-error"),e.data("unobtrusiveContainer",r),o?(r.empty(),e.removeClass("input-validation-error").appendTo(r)):e.hide()}function d(e,n){var t=a(this).find("[data-valmsg-summary=true]"),r=t.find("ul");r&&r.length&&n.errorList.length&&(r.empty(),t.addClass("validation-summary-errors").removeClass("validation-summary-valid"),a.each(n.errorList,function(){a("
  • ").html(this.message).appendTo(r)}))}function s(e){var n=e.data("unobtrusiveContainer");if(n){var t=n.attr("data-valmsg-replace"),r=t?a.parseJSON(t):null;n.addClass("field-validation-valid").removeClass("field-validation-error"),e.removeData("unobtrusiveContainer"),r&&n.empty()}}function l(e){var n=a(this),t="__jquery_unobtrusive_validation_form_reset";if(!n.data(t)){n.data(t,!0);try{n.data("validator").resetForm()}finally{n.removeData(t)}n.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors"),n.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}}function m(e){var n=a(e),t=n.data(v),r=a.proxy(l,e),i=p.unobtrusive.options||{},m=function(n,t){var r=i[n];r&&a.isFunction(r)&&r.apply(e,t)};return t||(t={options:{errorClass:i.errorClass||"input-validation-error",errorElement:i.errorElement||"span",errorPlacement:function(){o.apply(e,arguments),m("errorPlacement",arguments)},invalidHandler:function(){d.apply(e,arguments),m("invalidHandler",arguments)},messages:{},rules:{},success:function(){s.apply(e,arguments),m("success",arguments)}},attachValidation:function(){n.off("reset."+v,r).on("reset."+v,r).validate(this.options)},validate:function(){return n.validate(),n.valid()}},n.data(v,t)),t}var u,p=a.validator,v="unobtrusiveValidation";p.unobtrusive={adapters:[],parseElement:function(e,n){var t,r,i,o=a(e),d=o.parents("form")[0];d&&(t=m(d),t.options.rules[e.name]=r={},t.options.messages[e.name]=i={},a.each(this.adapters,function(){var n="data-val-"+this.name,t=o.attr(n),s={};void 0!==t&&(n+="-",a.each(this.params,function(){s[this]=o.attr(n+this)}),this.adapt({element:e,form:d,message:t,params:s,rules:r,messages:i}))}),a.extend(r,{__dummy__:!0}),n||t.attachValidation())},parse:function(e){var n=a(e),t=n.parents().addBack().filter("form").add(n.find("form")).has("[data-val=true]");n.find("[data-val=true]").each(function(){p.unobtrusive.parseElement(this,!0)}),t.each(function(){var a=m(this);a&&a.attachValidation()})}},u=p.unobtrusive.adapters,u.add=function(a,e,n){return n||(n=e,e=[]),this.push({name:a,params:e,adapt:n}),this},u.addBool=function(a,n){return this.add(a,function(t){e(t,n||a,!0)})},u.addMinMax=function(a,n,t,r,i,o){return this.add(a,[i||"min",o||"max"],function(a){var i=a.params.min,o=a.params.max;i&&o?e(a,r,[i,o]):i?e(a,n,i):o&&e(a,t,o)})},u.addSingleVal=function(a,n,t){return this.add(a,[n||"val"],function(r){e(r,t||a,r.params[n])})},p.addMethod("__dummy__",function(a,e,n){return!0}),p.addMethod("regex",function(a,e,n){var t;return this.optional(e)?!0:(t=new RegExp(n).exec(a),t&&0===t.index&&t[0].length===a.length)}),p.addMethod("nonalphamin",function(a,e,n){var t;return n&&(t=a.match(/\W/g),t=t&&t.length>=n),t}),p.methods.extension?(u.addSingleVal("accept","mimtype"),u.addSingleVal("extension","extension")):u.addSingleVal("extension","extension","accept"),u.addSingleVal("regex","pattern"),u.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url"),u.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range"),u.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength"),u.add("equalto",["other"],function(n){var o=r(n.element.name),d=n.params.other,s=i(d,o),l=a(n.form).find(":input").filter("[name='"+t(s)+"']")[0];e(n,"equalTo",l)}),u.add("required",function(a){("INPUT"!==a.element.tagName.toUpperCase()||"CHECKBOX"!==a.element.type.toUpperCase())&&e(a,"required",!0)}),u.add("remote",["url","type","additionalfields"],function(o){var d={url:o.params.url,type:o.params.type||"GET",data:{}},s=r(o.element.name);a.each(n(o.params.additionalfields||o.element.name),function(e,n){var r=i(n,s);d.data[r]=function(){var e=a(o.form).find(":input").filter("[name='"+t(r)+"']");return e.is(":checkbox")?e.filter(":checked").val()||e.filter(":hidden").val()||"":e.is(":radio")?e.filter(":checked").val()||"":e.val()}}),e(o,"remote",d)}),u.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&e(a,"minlength",a.params.min),a.params.nonalphamin&&e(a,"nonalphamin",a.params.nonalphamin),a.params.regex&&e(a,"regex",a.params.regex)}),a(function(){p.unobtrusive.parse(document)})}(jQuery); -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/jquery-validation/.bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jquery-validation", 3 | "homepage": "http://jqueryvalidation.org/", 4 | "repository": { 5 | "type": "git", 6 | "url": "git://github.com/jzaefferer/jquery-validation.git" 7 | }, 8 | "authors": [ 9 | "Jörn Zaefferer " 10 | ], 11 | "description": "Form validation made easy", 12 | "main": "dist/jquery.validate.js", 13 | "keywords": [ 14 | "forms", 15 | "validation", 16 | "validate" 17 | ], 18 | "license": "MIT", 19 | "ignore": [ 20 | "**/.*", 21 | "node_modules", 22 | "bower_components", 23 | "test", 24 | "demo", 25 | "lib" 26 | ], 27 | "dependencies": { 28 | "jquery": ">= 1.7.2" 29 | }, 30 | "version": "1.14.0", 31 | "_release": "1.14.0", 32 | "_resolution": { 33 | "type": "version", 34 | "tag": "1.14.0", 35 | "commit": "c1343fb9823392aa9acbe1c3ffd337b8c92fed48" 36 | }, 37 | "_source": "git://github.com/jzaefferer/jquery-validation.git", 38 | "_target": ">=1.8", 39 | "_originalSource": "jquery-validation" 40 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/jquery-validation/LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | ===================== 3 | 4 | Copyright Jörn Zaefferer 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/jquery-validation/dist/additional-methods.min.js: -------------------------------------------------------------------------------- 1 | /*! jQuery Validation Plugin - v1.14.0 - 6/30/2015 2 | * http://jqueryvalidation.org/ 3 | * Copyright (c) 2015 Jörn Zaefferer; Licensed MIT */ 4 | !function(a){"function"==typeof define&&define.amd?define(["jquery","./jquery.validate.min"],a):a(jQuery)}(function(a){!function(){function b(a){return a.replace(/<.[^<>]*?>/g," ").replace(/ | /gi," ").replace(/[.(),;:!?%#$'\"_+=\/\-“”’]*/g,"")}a.validator.addMethod("maxWords",function(a,c,d){return this.optional(c)||b(a).match(/\b\w+\b/g).length<=d},a.validator.format("Please enter {0} words or less.")),a.validator.addMethod("minWords",function(a,c,d){return this.optional(c)||b(a).match(/\b\w+\b/g).length>=d},a.validator.format("Please enter at least {0} words.")),a.validator.addMethod("rangeWords",function(a,c,d){var e=b(a),f=/\b\w+\b/g;return this.optional(c)||e.match(f).length>=d[0]&&e.match(f).length<=d[1]},a.validator.format("Please enter between {0} and {1} words."))}(),a.validator.addMethod("accept",function(b,c,d){var e,f,g="string"==typeof d?d.replace(/\s/g,"").replace(/,/g,"|"):"image/*",h=this.optional(c);if(h)return h;if("file"===a(c).attr("type")&&(g=g.replace(/\*/g,".*"),c.files&&c.files.length))for(e=0;ec;c++)d=h-c,e=f.substring(c,c+1),g+=d*e;return g%11===0},"Please specify a valid bank account number"),a.validator.addMethod("bankorgiroaccountNL",function(b,c){return this.optional(c)||a.validator.methods.bankaccountNL.call(this,b,c)||a.validator.methods.giroaccountNL.call(this,b,c)},"Please specify a valid bank or giro account number"),a.validator.addMethod("bic",function(a,b){return this.optional(b)||/^([A-Z]{6}[A-Z2-9][A-NP-Z1-2])(X{3}|[A-WY-Z0-9][A-Z0-9]{2})?$/.test(a)},"Please specify a valid BIC code"),a.validator.addMethod("cifES",function(a){"use strict";var b,c,d,e,f,g,h=[];if(a=a.toUpperCase(),!a.match("((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)"))return!1;for(d=0;9>d;d++)h[d]=parseInt(a.charAt(d),10);for(c=h[2]+h[4]+h[6],e=1;8>e;e+=2)f=(2*h[e]).toString(),g=f.charAt(1),c+=parseInt(f.charAt(0),10)+(""===g?0:parseInt(g,10));return/^[ABCDEFGHJNPQRSUVW]{1}/.test(a)?(c+="",b=10-parseInt(c.charAt(c.length-1),10),a+=b,h[8].toString()===String.fromCharCode(64+b)||h[8].toString()===a.charAt(a.length-1)):!1},"Please specify a valid CIF number."),a.validator.addMethod("cpfBR",function(a){if(a=a.replace(/([~!@#$%^&*()_+=`{}\[\]\-|\\:;'<>,.\/? ])+/g,""),11!==a.length)return!1;var b,c,d,e,f=0;if(b=parseInt(a.substring(9,10),10),c=parseInt(a.substring(10,11),10),d=function(a,b){var c=10*a%11;return(10===c||11===c)&&(c=0),c===b},""===a||"00000000000"===a||"11111111111"===a||"22222222222"===a||"33333333333"===a||"44444444444"===a||"55555555555"===a||"66666666666"===a||"77777777777"===a||"88888888888"===a||"99999999999"===a)return!1;for(e=1;9>=e;e++)f+=parseInt(a.substring(e-1,e),10)*(11-e);if(d(f,b)){for(f=0,e=1;10>=e;e++)f+=parseInt(a.substring(e-1,e),10)*(12-e);return d(f,c)}return!1},"Please specify a valid CPF number"),a.validator.addMethod("creditcardtypes",function(a,b,c){if(/[^0-9\-]+/.test(a))return!1;a=a.replace(/\D/g,"");var d=0;return c.mastercard&&(d|=1),c.visa&&(d|=2),c.amex&&(d|=4),c.dinersclub&&(d|=8),c.enroute&&(d|=16),c.discover&&(d|=32),c.jcb&&(d|=64),c.unknown&&(d|=128),c.all&&(d=255),1&d&&/^(5[12345])/.test(a)?16===a.length:2&d&&/^(4)/.test(a)?16===a.length:4&d&&/^(3[47])/.test(a)?15===a.length:8&d&&/^(3(0[012345]|[68]))/.test(a)?14===a.length:16&d&&/^(2(014|149))/.test(a)?15===a.length:32&d&&/^(6011)/.test(a)?16===a.length:64&d&&/^(3)/.test(a)?16===a.length:64&d&&/^(2131|1800)/.test(a)?15===a.length:128&d?!0:!1},"Please enter a valid credit card number."),a.validator.addMethod("currency",function(a,b,c){var d,e="string"==typeof c,f=e?c:c[0],g=e?!0:c[1];return f=f.replace(/,/g,""),f=g?f+"]":f+"]?",d="^["+f+"([1-9]{1}[0-9]{0,2}(\\,[0-9]{3})*(\\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\\.[0-9]{0,2})?|0(\\.[0-9]{0,2})?|(\\.[0-9]{1,2})?)$",d=new RegExp(d),this.optional(b)||d.test(a)},"Please specify a valid currency"),a.validator.addMethod("dateFA",function(a,b){return this.optional(b)||/^[1-4]\d{3}\/((0?[1-6]\/((3[0-1])|([1-2][0-9])|(0?[1-9])))|((1[0-2]|(0?[7-9]))\/(30|([1-2][0-9])|(0?[1-9]))))$/.test(a)},a.validator.messages.date),a.validator.addMethod("dateITA",function(a,b){var c,d,e,f,g,h=!1,i=/^\d{1,2}\/\d{1,2}\/\d{4}$/;return i.test(a)?(c=a.split("/"),d=parseInt(c[0],10),e=parseInt(c[1],10),f=parseInt(c[2],10),g=new Date(Date.UTC(f,e-1,d,12,0,0,0)),h=g.getUTCFullYear()===f&&g.getUTCMonth()===e-1&&g.getUTCDate()===d?!0:!1):h=!1,this.optional(b)||h},a.validator.messages.date),a.validator.addMethod("dateNL",function(a,b){return this.optional(b)||/^(0?[1-9]|[12]\d|3[01])[\.\/\-](0?[1-9]|1[012])[\.\/\-]([12]\d)?(\d\d)$/.test(a)},a.validator.messages.date),a.validator.addMethod("extension",function(a,b,c){return c="string"==typeof c?c.replace(/,/g,"|"):"png|jpe?g|gif",this.optional(b)||a.match(new RegExp("\\.("+c+")$","i"))},a.validator.format("Please enter a value with a valid extension.")),a.validator.addMethod("giroaccountNL",function(a,b){return this.optional(b)||/^[0-9]{1,7}$/.test(a)},"Please specify a valid giro account number"),a.validator.addMethod("iban",function(a,b){if(this.optional(b))return!0;var c,d,e,f,g,h,i,j,k,l=a.replace(/ /g,"").toUpperCase(),m="",n=!0,o="",p="";if(c=l.substring(0,2),h={AL:"\\d{8}[\\dA-Z]{16}",AD:"\\d{8}[\\dA-Z]{12}",AT:"\\d{16}",AZ:"[\\dA-Z]{4}\\d{20}",BE:"\\d{12}",BH:"[A-Z]{4}[\\dA-Z]{14}",BA:"\\d{16}",BR:"\\d{23}[A-Z][\\dA-Z]",BG:"[A-Z]{4}\\d{6}[\\dA-Z]{8}",CR:"\\d{17}",HR:"\\d{17}",CY:"\\d{8}[\\dA-Z]{16}",CZ:"\\d{20}",DK:"\\d{14}",DO:"[A-Z]{4}\\d{20}",EE:"\\d{16}",FO:"\\d{14}",FI:"\\d{14}",FR:"\\d{10}[\\dA-Z]{11}\\d{2}",GE:"[\\dA-Z]{2}\\d{16}",DE:"\\d{18}",GI:"[A-Z]{4}[\\dA-Z]{15}",GR:"\\d{7}[\\dA-Z]{16}",GL:"\\d{14}",GT:"[\\dA-Z]{4}[\\dA-Z]{20}",HU:"\\d{24}",IS:"\\d{22}",IE:"[\\dA-Z]{4}\\d{14}",IL:"\\d{19}",IT:"[A-Z]\\d{10}[\\dA-Z]{12}",KZ:"\\d{3}[\\dA-Z]{13}",KW:"[A-Z]{4}[\\dA-Z]{22}",LV:"[A-Z]{4}[\\dA-Z]{13}",LB:"\\d{4}[\\dA-Z]{20}",LI:"\\d{5}[\\dA-Z]{12}",LT:"\\d{16}",LU:"\\d{3}[\\dA-Z]{13}",MK:"\\d{3}[\\dA-Z]{10}\\d{2}",MT:"[A-Z]{4}\\d{5}[\\dA-Z]{18}",MR:"\\d{23}",MU:"[A-Z]{4}\\d{19}[A-Z]{3}",MC:"\\d{10}[\\dA-Z]{11}\\d{2}",MD:"[\\dA-Z]{2}\\d{18}",ME:"\\d{18}",NL:"[A-Z]{4}\\d{10}",NO:"\\d{11}",PK:"[\\dA-Z]{4}\\d{16}",PS:"[\\dA-Z]{4}\\d{21}",PL:"\\d{24}",PT:"\\d{21}",RO:"[A-Z]{4}[\\dA-Z]{16}",SM:"[A-Z]\\d{10}[\\dA-Z]{12}",SA:"\\d{2}[\\dA-Z]{18}",RS:"\\d{18}",SK:"\\d{20}",SI:"\\d{15}",ES:"\\d{20}",SE:"\\d{20}",CH:"\\d{5}[\\dA-Z]{12}",TN:"\\d{20}",TR:"\\d{5}[\\dA-Z]{17}",AE:"\\d{3}\\d{16}",GB:"[A-Z]{4}\\d{14}",VG:"[\\dA-Z]{4}\\d{16}"},g=h[c],"undefined"!=typeof g&&(i=new RegExp("^[A-Z]{2}\\d{2}"+g+"$",""),!i.test(l)))return!1;for(d=l.substring(4,l.length)+l.substring(0,4),j=0;j9&&a.match(/^(?:(?:(?:00\s?|\+)44\s?|0)7(?:[1345789]\d{2}|624)\s?\d{3}\s?\d{3})$/)},"Please specify a valid mobile number"),a.validator.addMethod("nieES",function(a){"use strict";return a=a.toUpperCase(),a.match("((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)")?/^[T]{1}/.test(a)?a[8]===/^[T]{1}[A-Z0-9]{8}$/.test(a):/^[XYZ]{1}/.test(a)?a[8]==="TRWAGMYFPDXBNJZSQVHLCKE".charAt(a.replace("X","0").replace("Y","1").replace("Z","2").substring(0,8)%23):!1:!1},"Please specify a valid NIE number."),a.validator.addMethod("nifES",function(a){"use strict";return a=a.toUpperCase(),a.match("((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)")?/^[0-9]{8}[A-Z]{1}$/.test(a)?"TRWAGMYFPDXBNJZSQVHLCKE".charAt(a.substring(8,0)%23)===a.charAt(8):/^[KLM]{1}/.test(a)?a[8]===String.fromCharCode(64):!1:!1},"Please specify a valid NIF number."),jQuery.validator.addMethod("notEqualTo",function(b,c,d){return this.optional(c)||!a.validator.methods.equalTo.call(this,b,c,d)},"Please enter a different value, values must not be the same."),a.validator.addMethod("nowhitespace",function(a,b){return this.optional(b)||/^\S+$/i.test(a)},"No white space please"),a.validator.addMethod("pattern",function(a,b,c){return this.optional(b)?!0:("string"==typeof c&&(c=new RegExp("^(?:"+c+")$")),c.test(a))},"Invalid format."),a.validator.addMethod("phoneNL",function(a,b){return this.optional(b)||/^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)[1-9]((\s|\s?\-\s?)?[0-9]){8}$/.test(a)},"Please specify a valid phone number."),a.validator.addMethod("phoneUK",function(a,b){return a=a.replace(/\(|\)|\s+|-/g,""),this.optional(b)||a.length>9&&a.match(/^(?:(?:(?:00\s?|\+)44\s?)|(?:\(?0))(?:\d{2}\)?\s?\d{4}\s?\d{4}|\d{3}\)?\s?\d{3}\s?\d{3,4}|\d{4}\)?\s?(?:\d{5}|\d{3}\s?\d{3})|\d{5}\)?\s?\d{4,5})$/)},"Please specify a valid phone number"),a.validator.addMethod("phoneUS",function(a,b){return a=a.replace(/\s+/g,""),this.optional(b)||a.length>9&&a.match(/^(\+?1-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/)},"Please specify a valid phone number"),a.validator.addMethod("phonesUK",function(a,b){return a=a.replace(/\(|\)|\s+|-/g,""),this.optional(b)||a.length>9&&a.match(/^(?:(?:(?:00\s?|\+)44\s?|0)(?:1\d{8,9}|[23]\d{9}|7(?:[1345789]\d{8}|624\d{6})))$/)},"Please specify a valid uk phone number"),a.validator.addMethod("postalCodeCA",function(a,b){return this.optional(b)||/^[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d$/.test(a)},"Please specify a valid postal code"),a.validator.addMethod("postalcodeBR",function(a,b){return this.optional(b)||/^\d{2}.\d{3}-\d{3}?$|^\d{5}-?\d{3}?$/.test(a)},"Informe um CEP válido."),a.validator.addMethod("postalcodeIT",function(a,b){return this.optional(b)||/^\d{5}$/.test(a)},"Please specify a valid postal code"),a.validator.addMethod("postalcodeNL",function(a,b){return this.optional(b)||/^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/.test(a)},"Please specify a valid postal code"),a.validator.addMethod("postcodeUK",function(a,b){return this.optional(b)||/^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))\s?([0-9][ABD-HJLNP-UW-Z]{2})|(GIR)\s?(0AA))$/i.test(a)},"Please specify a valid UK postcode"),a.validator.addMethod("require_from_group",function(b,c,d){var e=a(d[1],c.form),f=e.eq(0),g=f.data("valid_req_grp")?f.data("valid_req_grp"):a.extend({},this),h=e.filter(function(){return g.elementValue(this)}).length>=d[0];return f.data("valid_req_grp",g),a(c).data("being_validated")||(e.data("being_validated",!0),e.each(function(){g.element(this)}),e.data("being_validated",!1)),h},a.validator.format("Please fill at least {0} of these fields.")),a.validator.addMethod("skip_or_fill_minimum",function(b,c,d){var e=a(d[1],c.form),f=e.eq(0),g=f.data("valid_skip")?f.data("valid_skip"):a.extend({},this),h=e.filter(function(){return g.elementValue(this)}).length,i=0===h||h>=d[0];return f.data("valid_skip",g),a(c).data("being_validated")||(e.data("being_validated",!0),e.each(function(){g.element(this)}),e.data("being_validated",!1)),i},a.validator.format("Please either skip these fields or fill at least {0} of them.")),a.validator.addMethod("stateUS",function(a,b,c){var d,e="undefined"==typeof c,f=e||"undefined"==typeof c.caseSensitive?!1:c.caseSensitive,g=e||"undefined"==typeof c.includeTerritories?!1:c.includeTerritories,h=e||"undefined"==typeof c.includeMilitary?!1:c.includeMilitary;return d=g||h?g&&h?"^(A[AEKLPRSZ]|C[AOT]|D[CE]|FL|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEINOPST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$":g?"^(A[KLRSZ]|C[AOT]|D[CE]|FL|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEINOPST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$":"^(A[AEKLPRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])$":"^(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])$",d=f?new RegExp(d):new RegExp(d,"i"),this.optional(b)||d.test(a)},"Please specify a valid state"),a.validator.addMethod("strippedminlength",function(b,c,d){return a(b).text().length>=d},a.validator.format("Please enter at least {0} characters")),a.validator.addMethod("time",function(a,b){return this.optional(b)||/^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(a)},"Please enter a valid time, between 00:00 and 23:59"),a.validator.addMethod("time12h",function(a,b){return this.optional(b)||/^((0?[1-9]|1[012])(:[0-5]\d){1,2}(\ ?[AP]M))$/i.test(a)},"Please enter a valid time in 12-hour am/pm format"),a.validator.addMethod("url2",function(a,b){return this.optional(b)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(a)},a.validator.messages.url),a.validator.addMethod("vinUS",function(a){if(17!==a.length)return!1;var b,c,d,e,f,g,h=["A","B","C","D","E","F","G","H","J","K","L","M","N","P","R","S","T","U","V","W","X","Y","Z"],i=[1,2,3,4,5,6,7,8,1,2,3,4,5,7,9,2,3,4,5,6,7,8,9],j=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2],k=0;for(b=0;17>b;b++){if(e=j[b],d=a.slice(b,b+1),8===b&&(g=d),isNaN(d)){for(c=0;c").attr("name",c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)),e=c.settings.submitHandler.call(c,c.currentForm,b),c.submitButton&&d.remove(),void 0!==e?e:!1):!0}return c.settings.debug&&b.preventDefault(),c.cancelSubmit?(c.cancelSubmit=!1,d()):c.form()?c.pendingRequest?(c.formSubmitted=!0,!1):d():(c.focusInvalid(),!1)})),c)},valid:function(){var b,c,d;return a(this[0]).is("form")?b=this.validate().form():(d=[],b=!0,c=a(this[0].form).validate(),this.each(function(){b=c.element(this)&&b,d=d.concat(c.errorList)}),c.errorList=d),b},rules:function(b,c){var d,e,f,g,h,i,j=this[0];if(b)switch(d=a.data(j.form,"validator").settings,e=d.rules,f=a.validator.staticRules(j),b){case"add":a.extend(f,a.validator.normalizeRule(c)),delete f.messages,e[j.name]=f,c.messages&&(d.messages[j.name]=a.extend(d.messages[j.name],c.messages));break;case"remove":return c?(i={},a.each(c.split(/\s/),function(b,c){i[c]=f[c],delete f[c],"required"===c&&a(j).removeAttr("aria-required")}),i):(delete e[j.name],f)}return g=a.validator.normalizeRules(a.extend({},a.validator.classRules(j),a.validator.attributeRules(j),a.validator.dataRules(j),a.validator.staticRules(j)),j),g.required&&(h=g.required,delete g.required,g=a.extend({required:h},g),a(j).attr("aria-required","true")),g.remote&&(h=g.remote,delete g.remote,g=a.extend(g,{remote:h})),g}}),a.extend(a.expr[":"],{blank:function(b){return!a.trim(""+a(b).val())},filled:function(b){return!!a.trim(""+a(b).val())},unchecked:function(b){return!a(b).prop("checked")}}),a.validator=function(b,c){this.settings=a.extend(!0,{},a.validator.defaults,b),this.currentForm=c,this.init()},a.validator.format=function(b,c){return 1===arguments.length?function(){var c=a.makeArray(arguments);return c.unshift(b),a.validator.format.apply(this,c)}:(arguments.length>2&&c.constructor!==Array&&(c=a.makeArray(arguments).slice(1)),c.constructor!==Array&&(c=[c]),a.each(c,function(a,c){b=b.replace(new RegExp("\\{"+a+"\\}","g"),function(){return c})}),b)},a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(a){this.lastActive=a,this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(a)))},onfocusout:function(a){this.checkable(a)||!(a.name in this.submitted)&&this.optional(a)||this.element(a)},onkeyup:function(b,c){var d=[16,17,18,20,35,36,37,38,39,40,45,144,225];9===c.which&&""===this.elementValue(b)||-1!==a.inArray(c.keyCode,d)||(b.name in this.submitted||b===this.lastElement)&&this.element(b)},onclick:function(a){a.name in this.submitted?this.element(a):a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).addClass(c).removeClass(d):a(b).addClass(c).removeClass(d)},unhighlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).removeClass(c).addClass(d):a(b).removeClass(c).addClass(d)}},setDefaults:function(b){a.extend(a.validator.defaults,b)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date ( ISO ).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function b(b){var c=a.data(this.form,"validator"),d="on"+b.type.replace(/^validate/,""),e=c.settings;e[d]&&!a(this).is(e.ignore)&&e[d].call(c,this,b)}this.labelContainer=a(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm),this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var c,d=this.groups={};a.each(this.settings.groups,function(b,c){"string"==typeof c&&(c=c.split(/\s/)),a.each(c,function(a,c){d[c]=b})}),c=this.settings.rules,a.each(c,function(b,d){c[b]=a.validator.normalizeRule(d)}),a(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox']",b).on("click.validate","select, option, [type='radio'], [type='checkbox']",b),this.settings.invalidHandler&&a(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler),a(this.currentForm).find("[required], [data-rule-required], .required").attr("aria-required","true")},form:function(){return this.checkForm(),a.extend(this.submitted,this.errorMap),this.invalid=a.extend({},this.errorMap),this.valid()||a(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(b){var c=this.clean(b),d=this.validationTargetFor(c),e=!0;return this.lastElement=d,void 0===d?delete this.invalid[c.name]:(this.prepareElement(d),this.currentElements=a(d),e=this.check(d)!==!1,e?delete this.invalid[d.name]:this.invalid[d.name]=!0),a(b).attr("aria-invalid",!e),this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),e},showErrors:function(b){if(b){a.extend(this.errorMap,b),this.errorList=[];for(var c in b)this.errorList.push({message:b[c],element:this.findByName(c)[0]});this.successList=a.grep(this.successList,function(a){return!(a.name in b)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){a.fn.resetForm&&a(this.currentForm).resetForm(),this.submitted={},this.lastElement=null,this.prepareForm(),this.hideErrors();var b,c=this.elements().removeData("previousValue").removeAttr("aria-invalid");if(this.settings.unhighlight)for(b=0;c[b];b++)this.settings.unhighlight.call(this,c[b],this.settings.errorClass,"");else c.removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b,c=0;for(b in a)c++;return c},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(a){a.not(this.containers).text(""),this.addWrapper(a).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(b){}},findLastActive:function(){var b=this.lastActive;return b&&1===a.grep(this.errorList,function(a){return a.element.name===b.name}).length&&b},elements:function(){var b=this,c={};return a(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){return!this.name&&b.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.name in c||!b.objectLength(a(this).rules())?!1:(c[this.name]=!0,!0)})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.split(" ").join(".");return a(this.settings.errorElement+"."+b,this.errorContext)},reset:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=a([]),this.toHide=a([]),this.currentElements=a([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset(),this.toHide=this.errorsFor(a)},elementValue:function(b){var c,d=a(b),e=b.type;return"radio"===e||"checkbox"===e?this.findByName(b.name).filter(":checked").val():"number"===e&&"undefined"!=typeof b.validity?b.validity.badInput?!1:d.val():(c=d.val(),"string"==typeof c?c.replace(/\r/g,""):c)},check:function(b){b=this.validationTargetFor(this.clean(b));var c,d,e,f=a(b).rules(),g=a.map(f,function(a,b){return b}).length,h=!1,i=this.elementValue(b);for(d in f){e={method:d,parameters:f[d]};try{if(c=a.validator.methods[d].call(this,i,b,e.parameters),"dependency-mismatch"===c&&1===g){h=!0;continue}if(h=!1,"pending"===c)return void(this.toHide=this.toHide.not(this.errorsFor(b)));if(!c)return this.formatAndAdd(b,e),!1}catch(j){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+b.id+", check the '"+e.method+"' method.",j),j instanceof TypeError&&(j.message+=". Exception occurred when checking element "+b.id+", check the '"+e.method+"' method."),j}}if(!h)return this.objectLength(f)&&this.successList.push(b),!0},customDataMessage:function(b,c){return a(b).data("msg"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase())||a(b).data("msg")},customMessage:function(a,b){var c=this.settings.messages[a];return c&&(c.constructor===String?c:c[b])},findDefined:function(){for(var a=0;aWarning: No message defined for "+b.name+"")},formatAndAdd:function(b,c){var d=this.defaultMessage(b,c.method),e=/\$?\{(\d+)\}/g;"function"==typeof d?d=d.call(this,c.parameters,b):e.test(d)&&(d=a.validator.format(d.replace(e,"{$1}"),c.parameters)),this.errorList.push({message:d,element:b,method:c.method}),this.errorMap[b.name]=d,this.submitted[b.name]=d},addWrapper:function(a){return this.settings.wrapper&&(a=a.add(a.parent(this.settings.wrapper))),a},defaultShowErrors:function(){var a,b,c;for(a=0;this.errorList[a];a++)c=this.errorList[a],this.settings.highlight&&this.settings.highlight.call(this,c.element,this.settings.errorClass,this.settings.validClass),this.showLabel(c.element,c.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight)for(a=0,b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return a(this.errorList).map(function(){return this.element})},showLabel:function(b,c){var d,e,f,g=this.errorsFor(b),h=this.idOrName(b),i=a(b).attr("aria-describedby");g.length?(g.removeClass(this.settings.validClass).addClass(this.settings.errorClass),g.html(c)):(g=a("<"+this.settings.errorElement+">").attr("id",h+"-error").addClass(this.settings.errorClass).html(c||""),d=g,this.settings.wrapper&&(d=g.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(d):this.settings.errorPlacement?this.settings.errorPlacement(d,a(b)):d.insertAfter(b),g.is("label")?g.attr("for",h):0===g.parents("label[for='"+h+"']").length&&(f=g.attr("id").replace(/(:|\.|\[|\]|\$)/g,"\\$1"),i?i.match(new RegExp("\\b"+f+"\\b"))||(i+=" "+f):i=f,a(b).attr("aria-describedby",i),e=this.groups[b.name],e&&a.each(this.groups,function(b,c){c===e&&a("[name='"+b+"']",this.currentForm).attr("aria-describedby",g.attr("id"))}))),!c&&this.settings.success&&(g.text(""),"string"==typeof this.settings.success?g.addClass(this.settings.success):this.settings.success(g,b)),this.toShow=this.toShow.add(g)},errorsFor:function(b){var c=this.idOrName(b),d=a(b).attr("aria-describedby"),e="label[for='"+c+"'], label[for='"+c+"'] *";return d&&(e=e+", #"+d.replace(/\s+/g,", #")),this.errors().filter(e)},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(b){return this.checkable(b)&&(b=this.findByName(b.name)),a(b).not(this.settings.ignore)[0]},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(b){return a(this.currentForm).find("[name='"+b+"']")},getLength:function(b,c){switch(c.nodeName.toLowerCase()){case"select":return a("option:selected",c).length;case"input":if(this.checkable(c))return this.findByName(c.name).filter(":checked").length}return b.length},depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):!0},dependTypes:{"boolean":function(a){return a},string:function(b,c){return!!a(b,c.form).length},"function":function(a,b){return a(b)}},optional:function(b){var c=this.elementValue(b);return!a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(a){this.pending[a.name]||(this.pendingRequest++,this.pending[a.name]=!0)},stopRequest:function(b,c){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[b.name],c&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(a(this.currentForm).submit(),this.formSubmitted=!1):!c&&0===this.pendingRequest&&this.formSubmitted&&(a(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(b){return a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:!0,message:this.defaultMessage(b,"remote")})},destroy:function(){this.resetForm(),a(this.currentForm).off(".validate").removeData("validator")}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(b,c){b.constructor===String?this.classRuleSettings[b]=c:a.extend(this.classRuleSettings,b)},classRules:function(b){var c={},d=a(b).attr("class");return d&&a.each(d.split(" "),function(){this in a.validator.classRuleSettings&&a.extend(c,a.validator.classRuleSettings[this])}),c},normalizeAttributeRule:function(a,b,c,d){/min|max/.test(c)&&(null===b||/number|range|text/.test(b))&&(d=Number(d),isNaN(d)&&(d=void 0)),d||0===d?a[c]=d:b===c&&"range"!==b&&(a[c]=!0)},attributeRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)"required"===c?(d=b.getAttribute(c),""===d&&(d=!0),d=!!d):d=f.attr(c),this.normalizeAttributeRule(e,g,c,d);return e.maxlength&&/-1|2147483647|524288/.test(e.maxlength)&&delete e.maxlength,e},dataRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)d=f.data("rule"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase()),this.normalizeAttributeRule(e,g,c,d);return e},staticRules:function(b){var c={},d=a.data(b.form,"validator");return d.settings.rules&&(c=a.validator.normalizeRule(d.settings.rules[b.name])||{}),c},normalizeRules:function(b,c){return a.each(b,function(d,e){if(e===!1)return void delete b[d];if(e.param||e.depends){var f=!0;switch(typeof e.depends){case"string":f=!!a(e.depends,c.form).length;break;case"function":f=e.depends.call(c,c)}f?b[d]=void 0!==e.param?e.param:!0:delete b[d]}}),a.each(b,function(d,e){b[d]=a.isFunction(e)?e(c):e}),a.each(["minlength","maxlength"],function(){b[this]&&(b[this]=Number(b[this]))}),a.each(["rangelength","range"],function(){var c;b[this]&&(a.isArray(b[this])?b[this]=[Number(b[this][0]),Number(b[this][1])]:"string"==typeof b[this]&&(c=b[this].replace(/[\[\]]/g,"").split(/[\s,]+/),b[this]=[Number(c[0]),Number(c[1])]))}),a.validator.autoCreateRanges&&(null!=b.min&&null!=b.max&&(b.range=[b.min,b.max],delete b.min,delete b.max),null!=b.minlength&&null!=b.maxlength&&(b.rangelength=[b.minlength,b.maxlength],delete b.minlength,delete b.maxlength)),b},normalizeRule:function(b){if("string"==typeof b){var c={};a.each(b.split(/\s/),function(){c[this]=!0}),b=c}return b},addMethod:function(b,c,d){a.validator.methods[b]=c,a.validator.messages[b]=void 0!==d?d:a.validator.messages[b],c.length<3&&a.validator.addClassRules(b,a.validator.normalizeRule(b))},methods:{required:function(b,c,d){if(!this.depend(d,c))return"dependency-mismatch";if("select"===c.nodeName.toLowerCase()){var e=a(c).val();return e&&e.length>0}return this.checkable(c)?this.getLength(b,c)>0:b.length>0},email:function(a,b){return this.optional(b)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a)},url:function(a,b){return this.optional(b)||/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(a)},date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a).toString())},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a)},number:function(a,b){return this.optional(b)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9 \-]+/.test(a))return!1;var c,d,e=0,f=0,g=!1;if(a=a.replace(/\D/g,""),a.length<13||a.length>19)return!1;for(c=a.length-1;c>=0;c--)d=a.charAt(c),f=parseInt(d,10),g&&(f*=2)>9&&(f-=9),e+=f,g=!g;return e%10===0},minlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d},maxlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||d>=e},rangelength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d[0]&&e<=d[1]},min:function(a,b,c){return this.optional(b)||a>=c},max:function(a,b,c){return this.optional(b)||c>=a},range:function(a,b,c){return this.optional(b)||a>=c[0]&&a<=c[1]},equalTo:function(b,c,d){var e=a(d);return this.settings.onfocusout&&e.off(".validate-equalTo").on("blur.validate-equalTo",function(){a(c).valid()}),b===e.val()},remote:function(b,c,d){if(this.optional(c))return"dependency-mismatch";var e,f,g=this.previousValue(c);return this.settings.messages[c.name]||(this.settings.messages[c.name]={}),g.originalMessage=this.settings.messages[c.name].remote,this.settings.messages[c.name].remote=g.message,d="string"==typeof d&&{url:d}||d,g.old===b?g.valid:(g.old=b,e=this,this.startRequest(c),f={},f[c.name]=b,a.ajax(a.extend(!0,{mode:"abort",port:"validate"+c.name,dataType:"json",data:f,context:e.currentForm,success:function(d){var f,h,i,j=d===!0||"true"===d;e.settings.messages[c.name].remote=g.originalMessage,j?(i=e.formSubmitted,e.prepareElement(c),e.formSubmitted=i,e.successList.push(c),delete e.invalid[c.name],e.showErrors()):(f={},h=d||e.defaultMessage(c,"remote"),f[c.name]=g.message=a.isFunction(h)?h(b):h,e.invalid[c.name]=!0,e.showErrors(f)),g.valid=j,e.stopRequest(c,j)}},d)),"pending")}}});var b,c={};a.ajaxPrefilter?a.ajaxPrefilter(function(a,b,d){var e=a.port;"abort"===a.mode&&(c[e]&&c[e].abort(),c[e]=d)}):(b=a.ajax,a.ajax=function(d){var e=("mode"in d?d:a.ajaxSettings).mode,f=("port"in d?d:a.ajaxSettings).port;return"abort"===e?(c[f]&&c[f].abort(),c[f]=b.apply(this,arguments),c[f]):b.apply(this,arguments)})}); -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/jquery/.bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jquery", 3 | "version": "2.1.4", 4 | "main": "dist/jquery.js", 5 | "license": "MIT", 6 | "ignore": [ 7 | "**/.*", 8 | "build", 9 | "dist/cdn", 10 | "speed", 11 | "test", 12 | "*.md", 13 | "AUTHORS.txt", 14 | "Gruntfile.js", 15 | "package.json" 16 | ], 17 | "devDependencies": { 18 | "sizzle": "2.1.1-jquery.2.1.2", 19 | "requirejs": "2.1.10", 20 | "qunit": "1.14.0", 21 | "sinon": "1.8.1" 22 | }, 23 | "keywords": [ 24 | "jquery", 25 | "javascript", 26 | "library" 27 | ], 28 | "homepage": "https://github.com/jquery/jquery", 29 | "_release": "2.1.4", 30 | "_resolution": { 31 | "type": "version", 32 | "tag": "2.1.4", 33 | "commit": "7751e69b615c6eca6f783a81e292a55725af6b85" 34 | }, 35 | "_source": "git://github.com/jquery/jquery.git", 36 | "_target": "2.1.4", 37 | "_originalSource": "jquery" 38 | } -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/lib/jquery/MIT-LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2014 jQuery Foundation and other contributors 2 | http://jquery.com/ 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/NotFoundMiddlewareSample/wwwroot/web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | --------------------------------------------------------------------------------