locked
Blazor WASM w Identity Server - internal server error 500 RRS feed

  • Question

  • User379720387 posted

    Created a new Blazor WASM app with Identity Server, and went through the entire setup. Created a new user. FetchData works.

    From a the same app but without Identity Server, I copie the controller and a razor pages. Hooked every thing with EF Core  etc. AFAIK everthing is cool.

    I was expecting the razor page to load and get data from the controller just like it does in the app without Identity Server, however I get:

    info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
          Authorization was successful.
    blazor.webassembly.js:1 info: System.Net.Http.HttpClient.AMwAuth.ServerAPI.LogicalHandler[100]
          Start processing HTTP request GET https://localhost:44390/api/UserName/All
    blazor.webassembly.js:1 info: System.Net.Http.HttpClient.AMwAuth.ServerAPI.ClientHandler[100]
          Sending HTTP request GET https://localhost:44390/api/UserName/All
    2blazor.webassembly.js:1 info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
          Authorization was successful.
    api/UserName/All:1 Failed to load resource: the server responded with a status of 500 ()
    blazor.webassembly.js:1 info: System.Net.Http.HttpClient.AMwAuth.ServerAPI.ClientHandler[101]
          Received HTTP response headers after 159.4699ms - 500
    blazor.webassembly.js:1 info: System.Net.Http.HttpClient.AMwAuth.ServerAPI.LogicalHandler[101]
          End processing HTTP request after 291.695ms - 500
    blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
          Unhandled exception rendering component: Response status code does not indicate success: 500 (Internal Server Error).
    System.Net.Http.HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).
       at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
       at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__9`1[[AMwAuth.Shared.UserName[], AMwAuth.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
       at AMwAuth.Client.Pages.Accounts.OnInitializedAsync() in C:\Users\Robert\source\Repos\AMwAuth\Client\Pages\Accounts.razor:line 101
       at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
       at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)

    From what I see in FetchData and Weatherforecast Controller there is just very little that is IdentityServer related.

    My razor page:

    @page "/accounts"
    
    @using Microsoft.AspNetCore.Authorization
    @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
    @using AMwAuth.Shared
    
    @attribute [Authorize]
    
    @inject HttpClient http
    @inject NavigationManager navManager
    @inject ISnackbar Snackbar
    @inject IDialogService DialogService
    
    // markup removed
    
    @code {
    
        private bool dense = true;
        private bool hover = true;
        private bool ronly = false;
        private bool striped = true;
        private bool fixhdr = false;
        public bool Loading { get; set; }
        private int rows = 16;
        string snackMsg = "";
        private string searchString = "";
        private UserName selectedItem = null;
        private UserName[] usernames;
        UserName newAccount = new UserName();
    
        protected override async Task OnInitializedAsync()
        {
            Loading = true;
    
            //await LoadUserNames();
    
            usernames = await http.GetFromJsonAsync<UserName[]>("api/UserName/All");
    
            snackMsg = String.Format("{0} records retrieved", usernames.Count());
            Snackbar.Add(snackMsg, Severity.Success);
    
            Loading = false;
        }

    And the controller:

    using AMwAuth.Server.Models;
    using AMwAuth.Shared;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.EntityFrameworkCore;
    
    namespace AMwAuth.Server.Controllers
    {
        [Authorize]
        [ApiController]
        [Route("api/[controller]")]
        public class UserNameController : ControllerBase
        {
            private readonly UserManager<ApplicationUser> userManager;
            private readonly ILogger<UserNameController> _logger;
    
            public UserNameController(ILogger<UserNameController> logger,
                UserManager<ApplicationUser> userManager)
            {
                _logger = logger;
                this.userManager = userManager;
            }
    
            private readonly SchoolDBContext _context;
    
            public UserNameController(SchoolDBContext context)
            {
                this._context = context;
            }
    
            [Route("All")]
            [HttpGet]
            public async Task<ActionResult<List<Models.UserName>>> Get()
            {
                var user = await userManager.GetUserAsync(User);
                if (user != null)
                {
                    _logger.LogInformation($"User.Identity.Name: {user.UserName}");
                }
    
                return await _context.UserNames.ToListAsync();
            }

    All the yellow highlights are what was added for Identity Server

    The red highlight is line 101 from the exception.

    Not hitting a breakpoint in the razor page or the controller.

    What does the error message tell me?

    Am I missing something?

    What steps can I take for further troubleshooting?

    Saturday, May 15, 2021 11:43 PM

Answers

  • User379720387 posted

    Was encouraged to start looking at this to what could have broken what I had.

    As per previous suggestion by mgebhard I changed this:

    public async Task<ActionResult<List<UserName>>> Get()
            {
                return await _context.UserNames.ToListAsync();
            }

    to:

    public async Task<ActionResult<List<Models.UserName>>> Get()
            {
                var usernames = await _context.UserNames.ToListAsync();
    
    
                return usernames;
            }
    This allowed a different exception to surface where is was muttering about connection string and "source" not being valid.
    That lead me to appsettings.json where my connection string started with Source =, changed that to Server = and now all my breakpoints started working again and I got the data back from my api.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 18, 2021 4:40 PM

All replies

  • User475983607 posted

    It's not real clear what you copied or why.   The UserManager is an Identity API not not Identity Server.  

    The Web API code you've shared does not explain how the "User" is populated in Web API.  Can you explain the intended design?  Is the Web API hosted in Identity Server?  If so, did you secure Web API according the the Identity Server documentation.

    https://docs.identityserver.io/en/latest/topics/add_apis.html

    Sunday, May 16, 2021 9:57 AM
  • User379720387 posted

    From the templates that come with VS2019:

    App 1: Blazor Wasm hosted, no authentication has razor page to show usernames, data from UserNameController.

    App 2: New hosted Blazor Wasm app with authentication

    Added the UserNameController and Razor page from App 1 and decorated with the yellow highlighted items as show in OP.

    This app now has OidcConfigurationController, UserNameController, and WeatherForecastController with a connection string pointing to the local db that came with the template for Authentication, and another pointing to a db with the data I want to display (UserNames).

    Not understanding your question: "The Web API code you've shared does not explain how the "User" is populated in Web API."

    Sunday, May 16, 2021 12:31 PM
  • User379720387 posted

    Was encouraged to start looking at this to what could have broken what I had.

    As per previous suggestion by mgebhard I changed this:

    public async Task<ActionResult<List<UserName>>> Get()
            {
                return await _context.UserNames.ToListAsync();
            }

    to:

    public async Task<ActionResult<List<Models.UserName>>> Get()
            {
                var usernames = await _context.UserNames.ToListAsync();
    
    
                return usernames;
            }
    This allowed a different exception to surface where is was muttering about connection string and "source" not being valid.
    That lead me to appsettings.json where my connection string started with Source =, changed that to Server = and now all my breakpoints started working again and I got the data back from my api.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 18, 2021 4:40 PM