How can I check if a user is logged into the MVC5 Layout file

I have an MVC 5 site using _Layout shared browsing. In this _Layout view, I expose my scripts at the bottom, after the body.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    @*BootStrap must be loaded after JQuery UI in order to override the tooltip function*@
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/Session")

My problem now is that I want to include a Session Bundle on every page except my login pages. In other words, I want to use the Session Bundle only for pages where the user is logged in and they have an active session.

How can I check this condition in my _Layout view and render the script rendering?

On other pages, I would add a bool field to my model, and then use the C # If construct to display only the Script part if it is true, but I don't have a model in my _Layout view.

I also use custom, very simple login methods, so I do not use the Identity Framework MVC5.

EDIT I was asked to use the Request object

@if (Request.IsAuthenticated) { @Render...}

This does not work, since im uses a user login that does not work with the built-in infrastructure. I read how this field works here. How does Request.IsAuthenticated work?

The problem is still not resolved.

+4
source share
2 answers

I have found the answer.

access session variable from ASP.NET MVC3 RAZOR layout page

I can access the Session object from my layout. Using this, I can check if my user authentication object is equal. If it is not null, the user logs in

@if (Session["BrugerSession"] != null)
{
    @Scripts.Render("~/bundles/Session")
}
0
@if (Request.IsAuthenticated)
{
   // Render stuff for authenticated user
}
+7

Source: https://habr.com/ru/post/1626857/


All Articles