开发者

HttpContext in Razor Views

开发者 https://www.devze.com 2023-02-18 07:15 出处:网络
I tried to port some ASPX markup to Razor, but compiler threw an error. ASPX (works fine): <% if (node.IsAccessibleToUser(Context)) { %>

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

ASPX (works fine):

<% if (node.IsAccessibleToUser(Context)) { %>
    // markup
<% } %>
开发者_StackOverflow中文版

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?


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

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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号