Search code examples
asp.net-identityasp.net-core-2.0asp.net-core-viewcomponentrazor-class-library

Redirect to login page in asp.net core idenity in ViewComponent


I am trying to make my viewcomponent accessible only if user is logged in. I am checking if user is not authenticated then redirect to login page but following code is giving me error

public IViewComponentResult Invoke(int? id)
        {

            if (!User.Identity.IsAuthenticated)
            {   
                return View("~/Areas/Identity/Pages/Account/Login.cshtml");
            }
//other stuff
}

but this code is giving me error on login page

ArgumentNullException: Value cannot be null.
Parameter name: viewData

On Checking loginviewmodel it has overloaded constructor only that takes arguments

public LoginModel(SignInManager<IdentityUser> signInManager, ILogger<LoginModel> logger)

I can't figure out how to send these aruguments. Or there is a better way to redirect to login page


Solution

  • View components aren't part of the authorization pipeline. They're part of the view rendering pipeline, and by that point, it's too late to deny access or redirect. If the view component should not display if the user isn't logged in, then simply return an empty result, i.e. return Content(string.Empty);. Alternatively, you can gate it in your view:

    @if (User.Identity.IsAuthenticated)
    {
        @await Component.InvokeAsync("MyComponent")
    }
    

    The last part of your question is I think a complete misunderstanding of how things work here. A view component is just a way of rendering a partial while doing some sort of additional work a partial can't or shouldn't handle directly, such as injecting dependencies, querying a database, etc. Here, you're trying to return a Razor Page, which is not a partial. Razor Pages only work when directly routed to. The dependencies that you can't figure out how to satisfy are satisfied by the framework during the instantiating of the page model after routing.