0

I am trying to work through the MVC client quickstart but running into an "object reference not set ..." error at the line - "@foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)" from inside my Index.cshtml that I modified following the quickstart doc. Below is the complete Index.cshtml. Could somebody tell me what I am doing wrong here?

@using Microsoft.AspNetCore.Authentication

<h2>Claims</h2>

<dl>
    @foreach (var claim in User.Claims)
    {
        <dt>@claim.Type</dt>
        <dd>@claim.Value</dd>
    }
</dl>

<h2>Properties</h2>

<dl>
    @foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
    {
        <dt>@prop.Key</dt>
        <dd>@prop.Value</dd>
    }
</dl>
Alexu
  • 1,015
  • 2
  • 12
  • 32
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mxmissile Oct 02 '20 at 17:14
  • Not really but thanks for the input. I understand in general what NullReferenceException means and how to debug it. But in this case, VS doesn't tell me which reference in the line of code was null. And even if it did, I would have had no idea about how to fix it, as the entire Index.cshtml was created by copy and paste from quickstart doc. I suspect that the doc may not provide the complete contents of the file and so something needed are missing. I am new to MVC so I don't know what to look for. – Alexu Oct 02 '20 at 18:42
  • Lots you can do here, break that line up in different lines to easier see which command is throwing the exception, inspect it under you debugger. Also missing is what version of MVC your using, maybe link to the article where you got the code from, and what step in the application flow is this happening on? Give us more information so we can reproduce the problem. – mxmissile Oct 02 '20 at 19:28
  • Thank you so much mxmissile for the input! I am working with the latest qickstart of the IdentityServer4. And here is the doc I was following https://identityserver4.readthedocs.io/en/latest/quickstarts/2_interactive_aspnetcore.html. I am going to break the code up, as you suggested, and see what it turns out... Thanks again. – Alexu Oct 02 '20 at 19:49

1 Answers1

2

You are missing .RequireAuthorization(); on this part of code:

app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute()
        .RequireAuthorization();
});

The RequireAuthorization method disables anonymous access for the entire application.

Here I have a working example to follow: https://github.com/nahidf/IdentityServer4-adventures/tree/master/src/MvcClient

nahidf
  • 2,260
  • 1
  • 15
  • 22