vaindil
vaindil

Reputation: 7864

Using same route but show different content for authenticated/unauthenticated users

I'm building a new site on .NET 4.6, MVC 5. I want to use the same route for users whether they're logged in or not, but I want them to see the main home page when logged out and view their personal content when logged in. Facebook is an example of this--the URL for Facebook is facebook.com regardless of whether you're logged in or not.

I'm comfortable using any methods that are necessary, but I'm not sure how to best accomplish this.

Upvotes: 0

Views: 220

Answers (2)

firecape
firecape

Reputation: 726

For content that you want on every page, such as only showing certain nav bar links to those logged in, you can place the check for authentication directly in your layout view, something like the following:

@if (Request.IsAuthenticated)
{
    //only logged in users see this -- perhaps nav bar links or other site-wide content
}

You could also create a role or permission provider, so you can more finely control what sections show on the page based on roles, etc. Then do the same thing as above and check if the user is permitted based on what role they have, etc. This works great for only showing add or edit buttons based on the role they're in. Something like:

@if (Request.IsAuthenticated && User.IsInRole("Admin"))
{
    //only logged in users see this who are in the admin role
}

This can get messy of course if you do too much of this in your view, so as Wiktor Zychla explained above, you can also add properties for these in your model, and then only reference the model in your view.

But for things that will be site-wide (such as conditionally showing navbar links in the layout file), referencing Request or User in the view will do.

Upvotes: 2

Wiktor Zychla
Wiktor Zychla

Reputation: 48314

Feed your model data according to whether the user is or isn't authenticated. You can easily check this

this.User.Identity.IsAuthenticated

Depending on this you either conditionally build view content or even render some partial views, e.g.

// controller
model.ShowSomething = this.User.Identity.IsAuthenticated;

and then

@* view *@

@if ( Model.ShowSometing ) {
   Html.Partial( something that only authenticated users will see )
}

Remember your action should be accessible to anonymous users (no Authorize attribute).

Upvotes: 2

Related Questions