简体   繁体   中英

UserManager.GetUserAsync(User).Result.ProfilePicture Failing when Photo does not exists

I added the ability for users to add a photo to their profile as an avatar and ran into a problem. I then added a process to show the photo when the user logs in. However, I ran into a situation when a User is creating a new account. If a User creates an account and then tried to login, the Login failed. It appears that the Query to get the photo does not handle nulls in this case.

I tried to check for the photo first, just to be sure, but the code is failing in that check step.

                            @if (UserManager.GetUserAsync(User).Result.ProfilePicture.Length > 0 && UserManager.GetUserAsync(User).Result.ProfilePicture != null)
                            {
                                <li class="nav-link" style="align-self: center;">
                                    <img style="width:40px;height:40px; object-fit:cover; border-radius:30px;margin-right:-30px;" src="data:image/*;base64,@(Convert.ToBase64String(UserManager.GetUserAsync(User).Result.ProfilePicture))">
                                </li>
                            }

This is the Error that is generated. How do I safely check for the photo and only show one if it eixists, otherwise, gracefully display the menu without it?

An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Shared__Layout+<>c__DisplayClass54_0+<<ExecuteAsync>b__1>d.MoveNext() in _Layout.cshtml, line 102

Stack Query Cookies Headers Routing
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Shared__Layout+<>c__DisplayClass54_0+<<ExecuteAsync>b__1>d.MoveNext() in _Layout.cshtml
+
                            @if (UserManager.GetUserAsync(User).Result.ProfilePicture.Length > 0 && UserManager.GetUserAsync(User).Result.ProfilePicture != null)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
AspNetCore.Views_Shared__Layout.ExecuteAsync() in _Layout.cshtml
+
    var stats = "active";
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.RenderLayoutAsync(ViewContext context, ViewBufferTextWriter bodyWriter)
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(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.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

You're evaluating the length of ProfilePicture before you're checking if it's null. So,

Change:

@if (UserManager.GetUserAsync(User).Result.ProfilePicture.Length > 0 && UserManager.GetUserAsync(User).Result.ProfilePicture != null)

To:

@if (UserManager.GetUserAsync(User).Result.ProfilePicture != null && UserManager.GetUserAsync(User).Result.ProfilePicture.Length > 0)

If you're using the latest version of C#//Razor, I'd recommend doing:

@if (UserManager.GetUserAsync(User)?.Result?.ProfilePicture != null && UserManager.GetUserAsync(User)?.Result?.ProfilePicture?.Length > 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM