Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access Nancy's CurrentUser property from within a Razor view?

Tags:

razor

nancy

I am trying to access the CurrentUser property of the NancyContext. How do I do this from within the html of a Razor view?

I would be grateful for a code snippet if possible.

Thanks

Edit

I now extend Nancy.ViewEngines.Razor.HtmlHelpers to give me cross-view data with syntactic sugar that keeps the view code terse and readable.

Here are a few examples:

public static bool IsRegistered<T>(this HtmlHelpers<T> html)
{
    var user = GetUser(html);
    return user != null && user.IsRegistered;
}

public static bool IsAuthenticated<T>(this HtmlHelpers<T> html)
{
    return GetUser(html) != null;
}

public static User GetUser<T>(this HtmlHelpers<T> html)
{
    return (User)html.RenderContext.Context.CurrentUser;
}

And some razor code from a view. Here I am deciding to include the html for a Sign In popup (Foundation Reveal) only if the user is not currently authenticated - makes sense.

@if (!Html.IsAuthenticated())
{
    Html.Partial("Reveals/SignInReveal");
}  
like image 783
biofractal Avatar asked Jul 27 '12 13:07

biofractal


1 Answers

You can access the NancyContext through the Html property's RenderContext property.

A sample usage:

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>

<p>Current User: @Html.RenderContext.Context.CurrentUser </p>

However if your are using the SuperSimpleViewEngine (thanks the comment to @Sean) then you can do similar using the

@Context.CurrentUser.UserName
like image 79
nemesv Avatar answered Oct 22 '22 01:10

nemesv