Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to another page from _Layout.cshtml

How to redirect to another page within the _layout.cshtm page in asp.net core razor.

I am doing the verification and user is logged in, if not it will be redirected to another page.

@using Microsoft.AspNetCore.Identity
@using CronoParque.Model
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a asp-page="/Account/Manage/Index" title="Manage">Ola @UserManager.GetUserName(User)!</a>
            </li>
            <li>
                <button type="submit" class="btn btn-link navbar-btn navbar-link">Sair</button>
            </li>
        </ul>
    </form>
}
else
{
    // targeting here
}
like image 588
Renato Avatar asked Nov 16 '25 19:11

Renato


1 Answers

Answer

@if (SignInManager.IsSignedIn(User))
{
    // normal stuff
} 
else if (!Context.Request.Path.ToString().Contains("/About")) 
{
    // If we aren't processing a request for the target page, 
    // then redirect to it.
    Context.Response.Redirect("/About");
}

Maybe a Better Answer

The use case for your question might be to redirect unauthorized requests to a log in page. In that case, use the built-in razor pages authorization API.

services
    .AddMvc()
    .AddRazorPagesOptions(options => {
        options.Conventions.AuthorizePage("/Contact");
    });

The above code goes into the Startup > ConfigureServices method.

In the above example, the API redirects unauthorized requests for the /Contact.

See also: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/razor-pages-authorization?view=aspnetcore-2.1#require-authorization-to-access-a-page

like image 136
Shaun Luttin Avatar answered Nov 18 '25 10:11

Shaun Luttin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!