So, I’m trying to implement OpenIddict version 1.0.0-beta2-0580 with NET core 1.1 and I get the following error:
An unhandled exception occurred while processing the request
This is based on this : https://github.com/openiddict/openiddict-core/tree/dev/samples

The db registers the database correctly, the settings is loaded and everything works here. The tables in the db: __efmigrationshistory, aspnetroleclaims, aspnetroles, aspnetuserclaims, aspnetuserlogins, aspnetuserroles, aspnetusers, aspnetusertokens, basetransaction, openiddictapplications, openiddictauthorizations, openiddictscopes, openiddicttokens
And then I have the following stack trace :
InvalidOperationException: The authentication ticket was rejected because the mandatory subject claim was missing.
AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerHandler+<HandleSignInAsync>d__5.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Authentication.AuthenticationHandler+<SignInAsync>d__66.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager+<SignInAsync>d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.SignInResult+<ExecuteResultAsync>d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeResultAsync>d__30.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResultFilterAsync>d__28.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeAsync>d__20.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware+<ExecuteWithFilter>d__7.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()
In the startup I have :
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.RegisterDatabase(aspNet: true, useOpenIddict : true);
// Register the Identity services.
service.AddIdentity<User, IdentityRole>(config => { config.SignIn.RequireConfirmedEmail = requireConfirmEmail; })
.AddEntityFrameworkStores<DatabaseContext>()
.AddDefaultTokenProviders();
services.AddOpenIddict(options =>
{
// Register the Entity Framework stores.
options.AddEntityFrameworkCoreStores<DatabaseContext>();
// Register the ASP.NET Core MVC binder used by OpenIddict.
// Note: if you don't call this method, you won't be able to
// bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
options.AddMvcBinders();
// Enable the token endpoint.
options.EnableTokenEndpoint("/connect/token");
// Enable the password flow.
options.AllowPasswordFlow();
// During development, you can disable the HTTPS requirement.
options.DisableHttpsRequirement();
// Note: to use JWT access tokens instead of the default
// encrypted format, the following lines are required:
//
// options.UseJsonWebTokens();
// options.AddEphemeralSigningKey();
});
}
And then at the configure I have this :
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IServiceProvider service, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseOpenIddict();
// Create a new service scope to ensure the database context is correctly disposed when this methods returns.
using (var scope = service.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
await context.Database.MigrateAsync();
OpenIddictApplicationManager<OpenIddictApplication> manager = scope.ServiceProvider.GetRequiredService<OpenIddictApplicationManager<OpenIddictApplication>>();
// ---- Delete code comment ----------
// To test this sample with Postman, use the following settings:
//
// * Authorization URL: http://localhost:54540/connect/authorize
// * Access token URL: http://localhost:54540/connect/token
// * Client ID: postman
// * Client secret: [blank] (not used with public clients)
// * Scope: openid email profile roles
// * Grant type: authorization code
// * Request access token locally: yes
var client = await manager.FindByClientIdAsync("postman", cancellationToken);
if (client == null)
{
var application = new OpenIddictApplication
{
ClientId = "postman",
DisplayName = "Postman",
};
await manager.CreateAsync(application, cancellationToken);
}
}
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Then the auth controllers look like this:
public class AuthorizationController : Controller
{
private readonly SignInManager<User> _signInManager;
private readonly UserManager<User> _userManager;
public AuthorizationController(
SignInManager<User> signInManager,
UserManager<User> userManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
[HttpPost("~/connect/token"), Produces("application/json")]
public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
{
Debug.Assert(request.IsTokenRequest(),
"The OpenIddict binder for ASP.NET Core MVC is not registered. " +
"Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");
if (request.IsPasswordGrantType())
{
var user = await _userManager.FindByNameAsync(request.Username);
if (user == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The username/password couple is invalid."
});
}
// Ensure the user is allowed to sign in.
if (!await _signInManager.CanSignInAsync(user))
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The specified user is not allowed to sign in."
});
}
// Reject the token request if two-factor authentication has been enabled by the user.
if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user))
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The specified user is not allowed to sign in."
});
}
// Ensure the user is not already locked out.
if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user))
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The username/password couple is invalid."
});
}
// Ensure the password is valid.
if (!await _userManager.CheckPasswordAsync(user, request.Password))
{
if (_userManager.SupportsUserLockout)
{
await _userManager.AccessFailedAsync(user);
}
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The username/password couple is invalid."
});
}
if (_userManager.SupportsUserLockout)
{
await _userManager.ResetAccessFailedCountAsync(user);
}
// Create a new authentication ticket.
var ticket = await CreateTicketAsync(request, user);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
ErrorDescription = "The specified grant type is not supported."
});
}
private async Task<AuthenticationTicket> CreateTicketAsync(OpenIdConnectRequest request, User user)
{
// Create a new ClaimsPrincipal containing the claims that
// will be used to create an id_token, a token or a code.
var principal = await _signInManager.CreateUserPrincipalAsync(user);
// Note: by default, claims are NOT automatically included in the access and identity tokens.
// To allow OpenIddict to serialize them, you must attach them a destination, that specifies
// whether they should be included in access tokens, in identity tokens or in both.
foreach (var claim in principal.Claims)
{
// In this sample, every claim is serialized in both the access and the identity tokens.
// In a real world application, you'd probably want to exclude confidential claims
// or apply a claims policy based on the scopes requested by the client application.
claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
OpenIdConnectConstants.Destinations.IdentityToken);
}
// Create a new authentication ticket holding the user identity.
var ticket = new AuthenticationTicket(
principal, new AuthenticationProperties(),
OpenIdConnectServerDefaults.AuthenticationScheme);
// Set the list of scopes granted to the client application.
// Note: the offline_access scope must be granted
// to allow OpenIddict to return a refresh token.
ticket.SetScopes(new[]
{
OpenIdConnectConstants.Scopes.OpenId,
OpenIdConnectConstants.Scopes.Email,
OpenIdConnectConstants.Scopes.Profile,
OpenIdConnectConstants.Scopes.OfflineAccess,
OpenIddictConstants.Scopes.Roles
}.Intersect(request.GetScopes()));
return ticket;
}
}
The dependencies :
<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.2" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="1.1.0" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="1.1.2" />
<PackageReference Include="OpenIddict" Version="1.0.0-beta2-0615" />
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="1.0.0-beta2-0615" />
<PackageReference Include="OpenIddict.Mvc" Version="1.0.0-beta2-0615" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.1" />
</ItemGroup>
- Remove From My Forums
-
Question
-
User-190697402 posted
Hi ,
Im getting this error after trying to add Assets to StaffAssets table
InvalidOperationException: The instance of entity type 'StaffAssets' cannot be tracked because another instance with the same key value for {'StaffID'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.Here is what i have to acheive, My Assets tab will have Create New button,when i click on that it should navigate to Add Screen,

I should be able to add the assets for the employee

I should be able to add multiple Assets.Whats happening now is,when i add assets for the first its inserting record to StaffAssets table,but when im adding it for the second time,im getting the above mentioned error.
Answers
-
User1312693872 posted
Hi,teenajohn1989
If your problem is save the input data but show the last input data, then I have reproduced it.
You just need to put the query sentence into ‘if’ method, like my demo:
public async Task<IActionResult> OnPostInsertAssetsDetailsAsync(int current = 3) { if (ModelState.GetFieldValidationState("StaffAssets") == ModelValidationState.Valid) { await _context.StaffAssets.AddAsync(StaffAssets); await _context.SaveChangesAsync(); //when add works, then +1 ,means next tab currentTab = current; TempData["EmpID"] = StaffAssets.EmpID; TempData["StaffID"] = StaffAssets.StaffID; ShowStaffAssets = _context.StaffAssets.Where(c => c.StaffAssetName == StaffAssets.StaffAssetName).AsNoTracking().ToList(); return Page(); } else { var errors = ModelState.Values.SelectMany(v => v.Errors); return Page(); } }Result:

Best Regards,
Jerry Cai
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
-
User1312693872 posted
Hi,teenajohn1989
What is ‘not populate the already inserted one’ while you want to show all the added data means?
If you want to show all the assets, you just need to change the query in my demo to yours :
ShowStaffAssets = _context.StaffAssets.Where(c => c.StaffID == StaffAssets.StaffID).ToList();
Result:

If anything still wrong , you can share your create method, I’m not sure what you did in it.
<input type="button" class="btn-success" id="OnClickCreateStaffAsset" value="Create New" />
Best Regards,
Jerry Cai
-
Marked as answer by
Anonymous
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
-
User-190697402 posted
Hi Jerry Cai,
The display issue is fixed now.what i did is just add AsNoTracking() in the query
ShowStaffAssets = _context.StaffAssets.Where(c => c.StaffID == StaffAssets.StaffID).OrderBy(c => c.StaffAssetName).AsNoTracking().ToList();Thank you so much for the endless support and letting me know how to debug the LINQ query also.
-
Marked as answer by
Anonymous
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
using Host.AspNetCorePolicy;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.IdentityModel.Tokens.Jwt;
namespace Host
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
// this sets up a default authorization policy for the application
// in this case, authenticated users are required (besides controllers/actions that have [AllowAnonymous]
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
// this sets up authentication - for this demo we simply use a local cookie
// typically authentication would be done using an external provider
//services.AddAuthentication("Cookies")
// .AddCookie("Cookies");
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
//base address of identity server
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc";
options.ResponseType = "id_token";
options.SaveTokens = true;
options.Scope.Add("subject");
});
// this sets up the PolicyServer client library and policy provider - configuration is loaded from appsettings.json
services.AddPolicyServerClient(Configuration.GetSection("Policy"))
.AddAuthorizationPermissionPolicies();
// this adds the necessary handler for our custom medication requirement
services.AddTransient<IAuthorizationHandler, MedicationRequirementHandler>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
// add this middleware to make roles and permissions available as claims
// this is mainly useful for using the classic [Authorize(Roles="foo")] and IsInRole functionality
// this is not needed if you use the client library directly or the new policy-based authorization framework in ASP.NET Core
app.UsePolicyServerClaims();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute().RequireAuthorization();
});
}
}
Hi
I am doing a web application using asp.net core the problem is that I receive this error every time I launch the application I want to know what does that error mean
This Are Error Header:
An unhandled exception occurred while processing the request. FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list. System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, string format, ParamArray args)
This Are Error Details:
FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, string format, ParamsArray args)
string.FormatHelper(IFormatProvider provider, string format, ParamsArray args)
string.Format(IFormatProvider provider, string format, object arg0, object arg1)
System.ComponentModel.DataAnnotations.RegularExpressionAttribute.FormatErrorMessage(string name)
Microsoft.AspNetCore.Mvc.DataAnnotations.ValidationAttributeAdapter<TAttribute>.GetErrorMessage(ModelMetadata modelMetadata, object[] arguments)
Microsoft.AspNetCore.Mvc.DataAnnotations.Internal.RegularExpressionAttributeAdapter.GetErrorMessage(ModelValidationContextBase validationContext)
Microsoft.AspNetCore.Mvc.DataAnnotations.Internal.RegularExpressionAttributeAdapter.AddValidation(ClientModelValidationContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultValidationHtmlAttributeProvider.AddValidationAttributes(ViewContext viewContext, ModelExplorer modelExplorer, IDictionary<string, string> attributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.ValidationHtmlAttributeProvider.AddAndTrackValidationAttributes(ViewContext viewContext, ModelExplorer modelExplorer, string expression, IDictionary<string, string> attributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.AddValidationAttributes(ViewContext viewContext, TagBuilder tagBuilder, ModelExplorer modelExplorer, string expression)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateInput(ViewContext viewContext, InputType inputType, ModelExplorer modelExplorer, string expression, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, string format, IDictionary<string, object> htmlAttributes)
Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateTextBox(ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, string format, object htmlAttributes)
Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.GenerateTextBox(ModelExplorer modelExplorer, string inputTypeHint, string inputType, IDictionary<string, object> htmlAttributes)
Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Process(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
AspNetCore.Views_Contacts_Create.<ExecuteAsync>b__20_0() in Create.cshtml
+
<input asp-for="PhoneNumber" type="tel" class="form-control">
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
AspNetCore.Views_Contacts_Create.ExecuteAsync() in Create.cshtml
<big>+
ViewBag.Title = "Register";</big>
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync<TFilter, TFilterAsync>()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
This are the class that i defined validation
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Contact.Models { public class Contacts { public int ContactId { get; set; } [Required (ErrorMessage ="Please Provide A Value For First Name")] public string FirstName { get; set; } [Required (ErrorMessage ="Please Provide A Value For The Last Name")] public string LastName { get; set; } [Required(ErrorMessage ="Please Provide A Value For The WorkPlace ")] public string WorkPalce { get; set; } [Required(ErrorMessage ="Please Provide A Value For Phone Number")] [RegularExpression(@"^(01)[0-9]{9,}$", ErrorMessage = "The Phone Number Does Not Match The Pattern @(201)[0-9]{9}")] public int PhoneNumber { get; set; } [Required(ErrorMessage ="Please Provide Email Adress")] [RegularExpression(@"^([a-zA-Z0-9_-.]+)@([a-zA-Z0-9_-.]+).([a-zA-Z] {2,5})$", ErrorMessage ="Invalied Email Pattern")] public string Email { get; set; } [Required(ErrorMessage ="Please Provide A Data Of Birth")] [RegularExpression(@"^[0-9]{2}/[0-9]{2}/[0-9]{4}$", ErrorMessage ="Please Enter A valid Date Of Birth Matches Pattern DD/MM/YYYY")] public string DateOfBirth { get; set; } public string Note { get; set; } } }
This are the HTML CODE
@model Contacts
@{
ViewBag.Title = "Register";
}
<div class="container-fluid">
<form asp-action="Create" asp-controller="Contacts" method="post">
<div class="form-group">
<label asp-for="FirstName">First Name</label>
<input type="text" class="form-control" asp-for="FirstName">
<span asp-validation-for="FirstName"></span>
</div>
<div class="form-group">
<label asp-for="LastName">Last Name</label>
<input type="text" class="form-control" asp-for="LastName">
<span asp-validation-for="LastName"></span>
</div>
<div class="form-group">
<label asp-for="WorkPalce">Work</label>
<input type="text" class="form-control" asp-for="WorkPalce">
<span asp-validation-for="WorkPalce"></span>
</div>
<div class="form-group">
<label asp-for="PhoneNumber">Phone Number</label>
<input asp-for="PhoneNumber" type="tel" class="form-control">
<span asp-validation-for="PhoneNumber"></span>
</div>
<div class="form-group">
<label asp-for="Email">Email</label>
<input type="email" class="form-control" asp-for="Email">
<span asp-validation-for="Email"></span>
</div>
<div class="form-group">
<label asp-for="DateOfBirth">Date Of Birth</label>
<input type="date" class="form-control" asp-for="DateOfBirth">
<span asp-validation-for="DateOfBirth"></span>
</div>
<div class="form-group">
<label asp-for="Note">Comments</label>
<textarea class="form-control" asp-for="Note"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
Need to know what is the problem
What I have tried:
tried to remove the input for the phone number that makes the problem the app works and tried to change the regular expression for that input doesn’t work
Ряд пользователей браузеров при переходе на какой-либо сайт (наиболее часто данная проблема встречается на сайте Steam) могут столкнуться с ошибкой и соответствующим сообщением «An error occurred while processing your request». Обновление страницы проблемного сайта обычно ничего не даёт, пользователь сталкивается с упомянутой проблемой вновь и вновь. В этом материале я расскажу, что это за сообщение, при каких условиях появляется данная проблема, и как исправить её на вашем ПК.

Содержание
- Что такое An error occurred while processing your request
- Как исправить ошибку An error occurred
- Заключение
Что такое An error occurred while processing your request
В переводе с английского языка текст данной ошибки звучит как «Произошла ошибка во время обработки вашего запроса». Как уже упоминалось выше, наиболее часто на возникновение данной ошибки жалуются пользователи Steam, которые при переходе на данный сайт встречают описанную дисфункцию.

При этом данная ошибка может встречаться и на других ресурсах, и в абсолютном большинстве случаев имеет браузерную основу (пользователи различных онлайн-программ практически с ней не сталкиваются).
Причины данной ошибки следующие:
- Сбой или перегрузка сервера, обрабатывающего ваш запрос;
- Случайный сбой вашего ПК;
- Кэш вашего браузера повреждён;
- Ошибка SSL-сертификата вашего браузера;
- Проблемы с HTTPS-протоколом у ряда сайтов;
- Проблема с HTTPS-расширениями вашего браузера (например, с «HTTPS Everywhere»).
После определения причин дисфункции перейдём к описанию того, как избавиться от ошибки Sorry, an error occurred while processing your request.

Как исправить ошибку An error occurred
Итак, вы встретились с упомянутой проблемой и думаете, как её устранить. Рекомендую выполнить следующий ряд действий:
- Попробуйте просто перезагрузить свой компьютер. Это помогает чаще, чем может показаться;
- Немного подождите. Во многих случаях (особенно это касается пользователей Steam) сервера бывают перегружены или «упали», потому необходимо некоторое время для решения проблемы администрацией сервера. В подобных случаях нужно немного подождать (часто хватает и суток) чтобы проблема была решена;
- Очистите кэш и куки вашего браузера. К примеру, в браузере Мозилла это делается переходом в «Настройки», затем в закладку «Приватность», и кликом на «Удалить вашу недавнюю историю». В открывшимся окне «Удаление истории» в «Подробности» поставьте галочку на «Кэш» и удалите последний;

- Попробуйте сменить ваш браузер, использовав альтернативный веб-обозреватель при осуществлении перехода на проблемный сайт;
- Если вы не можете запустить игру Steam с браузера (через веб-лаунчер), попробуйте использовать находящийся на вашем ПК exe-файл данной игры для её запуска (сам файл часто находится в папке Steam);
- Удалите SSL-сертификат проблемного сайт. Удаление SSL-сертификата проблемного сайта, по отзывам пользователей, может помочь в решении ошибки An error occurred while processing your request. Как удалить проблемный сертификат описано;
- Попробуйте использовать не зашифрованную версию сайта (при возможности). Обычно адрес зашифрованного сайта начинается с https. Попробуйте использовать тот же адрес, но с началом на http (без окончания s), это может помочь в вопросе как пофиксить ошибку An error occurred while processing your request;

- Удалите (отключите) расширения браузера, принуждающие вебсайты работать только c HTTPS (например, уже упомянутое расширение «HTTPS Everywhere»);
- Если данная ошибка возникла при работе с социальной сетью (например, с Фейсбук), попробуйте выйти из неё, а потом вновь выполнить вход;
- Уведомьте администрацию проблемного ресурса о возникшей проблеме (обычно, хватает соответствующего письма в службу технической поддержки).
Заключение
В данном материале мной была рассмотрена тема «An error occurred while processing your request, что делать», обозначены причины данной проблемы и намечены пути её решения. В большинстве случаев данная ошибка возникает из-за перегрузки или «падения» серверов, и от пользователя требуется немного подождать, дабы всё пришло в норму. В иных же случаях попробуйте выполнить очистку кэша вашего браузера, так как именно этот совет оказался весьма эффективным в решении данной проблемы на пользовательских ПК.
Опубликовано 02.02.2017 Обновлено 19.02.2021
An unhandled exception occurred while processing the request.
AggregateException: One or more errors occurred. (One or more errors occurred. (Failed to start ‘npm’. To resolve this:.
[1] Ensure that ‘npm’ is installed and can be found in one of the PATH directories.
Current PATH enviroment variable is: C:Oracleproduct12.1.0dbhome_1bin;C:Program Files (x86)Common FilesOracleJavajavapath;C:windowssystem32;C:windows;C:windowsSystem32Wbem;C:windowsSystem32WindowsPowerShellv1.0;C:windowsSystem32OpenSSH;C:Program FilesTortoiseSVNbin;C:Program FilesMicrosoft SQL Server130ToolsBinn;C:Program FilesMicrosoft SQL ServerClient SDKODBC170ToolsBinn;C:UsersalguptaAppDataLocalProgramsGitcmd;C:Program Files (x86)Microsoft SQL Server150ToolsBinn;C:Program FilesMicrosoft SQL Server150ToolsBinn;C:Program Files (x86)Microsoft SQL Server150DTSBinn;C:Program FilesMicrosoft SQL Server150DTSBinn;C:Program FilesJavajdk1.8.0_231bin;C:Program Filesnodejs;C:Program Filesdotnet;C:Program FilesTortoiseGitbin;C:Program FilesPuTTY;C:UsersalguptaAppDataRoamingnpm;C:UsersalguptaAppDataLocalMicrosoftWindowsApps;C:Program Files (x86)SophosSophos SSL VPN Clientbin;C:Usersalgupta.dotnettools;C:UsersalguptaAppDataLocalProgramsMicrosoft VS Codebin
Make sure the executable is in one of those directories, or update your PATH.
[2] See the InnerException for further details of the cause.))
System.Threading.Tasks.Task.GetResultCore(bool waitCompletionNotification)
InvalidOperationException: Failed to start ‘npm’. To resolve this:.
[1] Ensure that ‘npm’ is installed and can be found in one of the PATH directories.
Current PATH enviroment variable is: C:Oracleproduct12.1.0dbhome_1bin;C:Program Files (x86)Common FilesOracleJavajavapath;C:windowssystem32;C:windows;C:windowsSystem32Wbem;C:windowsSystem32WindowsPowerShellv1.0;C:windowsSystem32OpenSSH;C:Program FilesTortoiseSVNbin;C:Program FilesMicrosoft SQL Server130ToolsBinn;C:Program FilesMicrosoft SQL ServerClient SDKODBC170ToolsBinn;C:UsersalguptaAppDataLocalProgramsGitcmd;C:Program Files (x86)Microsoft SQL Server150ToolsBinn;C:Program FilesMicrosoft SQL Server150ToolsBinn;C:Program Files (x86)Microsoft SQL Server150DTSBinn;C:Program FilesMicrosoft SQL Server150DTSBinn;C:Program FilesJavajdk1.8.0_231bin;C:Program Filesnodejs;C:Program Filesdotnet;C:Program FilesTortoiseGitbin;C:Program FilesPuTTY;C:UsersalguptaAppDataRoamingnpm;C:UsersalguptaAppDataLocalMicrosoftWindowsApps;C:Program Files (x86)SophosSophos SSL VPN Clientbin;C:Usersalgupta.dotnettools;C:UsersalguptaAppDataLocalProgramsMicrosoft VS Codebin
Make sure the executable is in one of those directories, or update your PATH.
[2] See the InnerException for further details of the cause.
Microsoft.AspNetCore.NodeServices.Npm.NpmScriptRunner.LaunchNodeProcess(ProcessStartInfo startInfo)