Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext in Razor Views

I tried to port some ASPX markup to Razor, but compiler threw an error.

ASPX (works fine):

<% if (node.IsAccessibleToUser(Context)) { %>
    // markup
<% } %>

CSHTML (throws an error):

@if (node.IsAccessibleToUser(Context)) {
    // markup
}

Argument 1: cannot convert from 'System.Web.HttpContextBase' to 'System.Web.HttpContext'

How to get reference to HttpContext in Razor view? Is it correct to use HttpContext.Current or I need to check site map node visibility in a different way?

like image 396
altso Avatar asked Mar 21 '11 12:03

altso


3 Answers

WebViewPage.Context is HttpContextBase instance. WebViewPage.Context.ApplicationInstance.Context is HttpContext instance.

@if (node.IsAccessibleToUser(Context.ApplicationInstance.Context)) {
    // markup
}
like image 93
takepara Avatar answered Nov 20 '22 04:11

takepara


Yes, you can use HttpContext.Current. This will give you access to the request and response data.

like image 28
Kim R Avatar answered Nov 20 '22 04:11

Kim R


What @Martin means is that you could write some extension methods on your Node class (whatever the type of that is), like:

public static class NodeExtensions
{
    public static bool IsAccessibleToUser(this Node node)
    {
        // access HttpContext through HttpContext.Current here 
    }
}

and use it in your view like:

@if(node.IsAccessibleToUser()) {}

Thus removing the dependency on HttpContext in your view.

like image 43
Sergi Papaseit Avatar answered Nov 20 '22 04:11

Sergi Papaseit