Autheracation error: Key cannot be null. Parameter name: key - asp.net-mvc-4

I keep getting the error Key cannot be null. Parameter name: key. It looks like it looses the authCookie, but the Request.IsAuthenticated still is set to true. It's driving my crazy. Also i'm allready handling if the user is not logged in. But the error still appears.
An place where it fails is fore example here
#if (User.IsInRole("Admin"))
{
<button class="button-green white">Save</button>
}
But if look at what the user has of properties it still says IsAuthenticated = true and the name and Role is also correct, and the ticket is still valid.
This is the callstack
System.ArgumentNullException was unhandled by user code
HResult=-2147467261
Message=Key cannot be null.
Parameter name: key
Source=System
ParamName=key
StackTrace:
at System.Collections.Specialized.HybridDictionary.get_Item(Object key)
at System.Web.Security.RolePrincipal.IsInRole(String role)
at ASP._Page_Views_Admin_EditText_cshtml.Execute() in d:\SubVersion\Oline\Project1\Source\Oline.Portal\Views\Admin\EditText.cshtml:line 78
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
InnerException:
This is my Custom RoleProvier
public override string[] GetRolesForUser(string username)
{
var user = (string)HttpContext.Current.Session["UserRoles"];
var ret = new[] { user };
return ret;
}

The solution to the problem was, this section var user = (string)HttpContext.Current.Session["UserRoles"];, that becomes null. Special then I go back and fort, changing things in Visual Studio 2012. Thanks for the suggestions :)

Related

UriFormatException getting caught in exception handler for ASP .Net Core

I've added exception handling to my Asp .Net Core application to log any unhandled exceptions. I am getting unhandled UriFormatExceptions within the middleware due to what appears to be traffic from various web crawlers targeting non-existent endpoints. I am not sure how to fix this, or at least elegantly silence it so it does not show up in my telemetry. In general, I'd like to ignore traffic hitting endpoints not defined by my application.
Exception logged
[Unhandled exception][UriString][https:///favicon.ico][Exception]
[System.UriFormatException: Invalid URI: The hostname could not be parsed.]
Stacktrace:
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind, UriCreationOptions& creationOptions)
at System.Uri..ctor(String uriString)
at Microsoft.AspNet.OData.Routing.ODataPathRouteConstraint.Match(HttpContext httpContext, IRouter route, String routeKey, RouteValueDictionary values, RouteDirection routeDirection)
at Microsoft.AspNetCore.Routing.RouteConstraintMatcher.Match(IDictionary`2 constraints, RouteValueDictionary routeValues, HttpContext httpContext, IRouter route, RouteDirection routeDirection, ILogger logger)
at Microsoft.AspNetCore.Routing.RouteBase.RouteAsync(RouteContext context)
at Microsoft.AspNetCore.Routing.RouteCollection.RouteAsync(RouteContext context)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)]
Exception Handler
app.UseExceptionHandler(exceptionHandlerApp =>
{
exceptionHandlerApp.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
IExceptionHandlerPathFeature exceptionHandlerPathFeature =
context.Features.Get<IExceptionHandlerPathFeature>();
string uriString = null;
uriString = context.Request.GetEncodedUrl();
Logger.EmitLog(
"Unhandled exception",
"UriString",
uriString,
"Exception",
exceptionHandlerPathFeature?.Error);
});
});

How should I cache data from database to be thread safe by EF Core?

I have a list of data, it is not large (about 400 items). It is stored in the MySQL database, and I want to cache it to ASP.NET Core to prevent reading it frequently. What's more, the data will refresh every hour.
Here is my code:
public class IPCheckService
{
readonly SIComponent.Database.BLContext Context;
public IPCheckService(SIComponent.Database.BLContext Context)
{
this.Context = Context;
}
List<SIComponent.Database.IPAndUAModel> _IPBlackList = null;
public List<SIComponent.Database.IPAndUAModel> IPBlackList
{
get
{
if (DateTime.Now - LastUpdateTime > TimeSpan.FromHours(2))
{
if (Context.IpBlackList.Count() != _IPRangeBlackList.Count)
{
_IPRangeBlackList = new List<SIComponent.Database.IPAndUAModel>(Context.IpBlackList);
}
LastUpdateTime = DateTime.Now;
}
if (_IPBlackList == null)
{
_IPBlackList = new List<SIComponent.Database.IPAndUAModel>(Context.IPBlackList);
}
return _IPBlackList;
}
}
DateTime LastUpdateTime = DateTime.Now;
}
What's more, the codes above are part of the service and it is a Singleton service.
After the program ran, the exception middleware I made will sometimes catch this exception:
An attempt was made to use the model while it was being created. A DbContext instance cannot be used inside 'OnModelCreating' in any way that makes use of the model that is being created.
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel(Boolean designTime)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at Microsoft.EntityFrameworkCore.DbContext.get_Model()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityType() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.CheckState()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityQueryable() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.System.Collections.Generic.IEnumerable.GetEnumerator()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at abc.Services.IPCheckService.get_IPBlackList() in C:\Project\abc\Services\IPCheckService.cs:line 12
at abc.Middlewares.IPAccessCheck(IPModel IP) in C:\Project\abc\Middlewares\IPAccessCheckMiddleware.cs:line 701
at lambda_method9(Closure , Object)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatcher|8_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task1 matcherTask)
at abc.Middlewares.ExceptionMiddleware.Invoke(HttpContext context) in C:\Project\abc\Middlewares\ExceptionMiddleware.cs:line 26
I read some articles about this exception and found it seems because instance members of DbContext and related classes are not guaranteed to be thread-safe.
However, I found nothing article about how to solve this. How should I solve it? Thank you.
You cannot use DbContext in such way. It is usually registered as scoped service, but you are trying to inject it into singletone. Also there are problems with multithreading, you have to guard retrieving data.
Well there is my variant:
public class IPCheckService
{
private readonly IServiceProvider _serviceProvider;
private DateTime _lastUpdateTime;
private List<SIComponent.Database.IPAndUAModel> _IPBlackList = null;
public IPCheckService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IReadOnlyList<SIComponent.Database.IPAndUAModel> IPBlackList
{
get
{
// you need lock because several threads may access this property concurrently.
lock(this)
{
if (_IPBlackList != null && (DateTime.Now - _lastUpdateTime).TotalHours < 1)
{
return _IPBlackList;
}
// context will be create within scope and automatically disposed
using (var scope = serviceProvider.CreateScope())
{
var context = scope.ServiceProvider.GetService<SIComponent.Database.BLContext>();
_IPBlackList = context.IPBlackList.ToList();
_lastUpdateTime = DateTime.Now;
}
return _IPBlackList
}
}
}
}

ASP.Net Core ODataController Attribute Routing throws 500 error during insert

I am trying to implement Create and update logic on my ODataController on ASP.Net core 5.0 using 8.0.0-beta. My controller looks like this:
[HttpPost]
[Route("users/{key}/{operation}")]
public async Task<IActionResult> UpdateUser([FromODataUri] string key, [FromODataUri] string operation, [FromBody] Delta<User> userPatch)
{
IActionResult result = BadRequest($"Key:{key} / Operation:{operation.ToLower()}");
if (operation.ToLower() == "update")
{
result = await Patch(key, userPatch);
return result;
}
else if (operation.ToLower() == "create")
{
var newUser = new User();
userPatch.Patch(newUser);
var entity = await AddNewEntity(newUser, key);
result = Created(entity);
}
return result;
}
The update is working fine, I am able to verify using the REST client(http://localhost:5000/users/MY-USER-6/update)
However when I call create method using the REST client (http://localhost:5000/users/MY-USER-6/create) I see that the method works and data is inserted in the database and function exits without an issue, however the result I get on the REST client the response says Status Code: 500 Internal Server Error with the following exception:
System.InvalidOperationException: The request must have an associated EDM model. Consider using the extension method HttpConfiguration.MapODataServiceRoute to register a route that parses the OData URI and attaches the model information.
at Microsoft.AspNetCore.OData.Results.ResultHelpers.GenerateODataLink(HttpRequest request, Object entity, Boolean isEntityId)
at Microsoft.AspNetCore.OData.Results.CreatedODataResult`1.GenerateLocationHeader(HttpRequest request)
at Microsoft.AspNetCore.OData.Results.CreatedODataResult`1.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
BTW if I change result = Created(entity); to result = Ok(entity); its working fine!
As per some blogs and channel9 videos I am trying to add endpoints.EnableDependencyInjection(); but looks like this is no longer available or may be valid in the 8.0.0-beta.
What am I missing in this?

The relative page path 'About' can only be used while executing a Razor Page. Specify a

First of all I have searched about this error and found nothing. The full exception:
System.InvalidOperationException: The relative page path 'About' can only be used while executing a Razor Page. Specify a root relative path with a leading '/' to generate a URL outside of a Razor Page.
at Microsoft.AspNetCore.Mvc.UrlHelperExtensions.CalculatePageName(ActionContext actionContext, String pageName)
at Microsoft.AspNetCore.Mvc.UrlHelperExtensions.Page(IUrlHelper urlHelper, String pageName, String pageHandler, Object values, String protocol, String host, String fragment)
at Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GeneratePageLink(ViewContext viewContext, String linkText, String pageName, String pageHandler, String protocol, String hostname, String fragment, Object routeValues, Object htmlAttributes)
at Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper.Process(TagHelperContext context, TagHelperOutput output)
at Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
at AspNetCore.Views_Shared__FooterPartial.ExecuteAsync()
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
at Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.RenderPartialViewAsync(TextWriter writer, Object model)
at Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
at AspNetCore.Views_Shared__Layout.<ExecuteAsync>b__40_1() in D:\Documents\Obaju\Obaju.App\Views\Shared\_Layout.cshtml:line 40
at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
at AspNetCore.Views_Shared__Layout.ExecuteAsync()
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderLayoutAsync(ViewContext context, ViewBufferTextWriter bodyWriter)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
About is Razor Page accesed via /about url path and it works well. This error happens only when I try to go on /home/index or another mvc view.
The Problem
In one of your Razor Views, there is an anchor tag that looks something like this:
<a asp-page="About">About</a>
That syntax (without the forward slash /) will only work inside a Razor Page.
The Solution
Inside a Razor View, prefix the Page name with a forward slash / like this:
<a asp-page="/About">About</a>
Distinguishing Razor Views from Razor Pages
Razor Views are usually in a Views directory.
Razor Pages are usually in a Pages directory and have an #page directive at the top of the file.
<a class="nav-link" asp-area="Identity" asp-page="/Account/Manage/ChangePassword">
For creating Razor Page link, add asp-area and then asp-page.

No Persister for: error on save with INotifyPropertyChanged Interceptor

Using the method described in NHibernate & INotifyPropertyChanged, the repository will return a collection of proxies that implement INotifyPropertyChanged, but on some objects when saving or deleting it will throw an error:
at NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
at NHibernate.Impl.SessionImpl.GetEntityPersister(String entityName, Object obj)
at NHibernate.Engine.ForeignKeys.IsTransient(String entityName, Object entity, Nullable`1 assumed, ISessionImplementor session)
at NHibernate.Event.Default.AbstractSaveEventListener.GetEntityState(Object entity, String entityName, EntityEntry entry, ISessionImplementor source)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj)
at MyCode ...
I figured out that if I create the session without the interceptor the SaveOrUpdate works fine, but with the interceptor it errors.
with the interceptor:
public ISession GetSession(ISessionFactory factory)
{
IInterceptor dataBinding = new DataBindingInterceptor {SessionFactory = factory};
return factory.OpenSession(dataBinding);
}
without
public ISession GetSession(ISessionFactory factory)
{
return factory.OpenSession();
}
I'm at a loss for how to go about even figuring out why the interceptor would break the save.
The only change I made to the code was changing the line
Type type = Type.GetType(clazz);
to
Type type = FindType(clazz);
public Type FindType(string typeName)
{
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Type foundType = assembly.GetType(typeName);
if (foundType != null)
return foundType;
}
return null;
}
Solution was to always use the session with the interceptor. I was creating the IList with the interceptor, but saving with a generic session. This bypassed the GetEntityName override which redirected the proxy to the correct persister.