MVC 4和Razor的扩展方法

rhu*_*hes 15 c# asp.net-mvc razor

我创建了一个扩展方法,并将其命名空间包含在我的web.config文件中.扩展方法工作正常,测试代码可以接受.问题是,我仍然收到与找不到命名空间有关的错误.

我得到的ASP .NET错误消息是:

CS1061:'System.Uri'不包含'IsCurrentUrl'的定义,并且没有扩展方法'IsCurrentUrl'接受类型'System.Uri'的第一个参数可以找到(你是否缺少using指令或程序集引用?)

以下是各自的代码.

Web.config文件:

<system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="true" targetFramework="4.5" />
    <pages>
        <namespaces>
            <add namespace="System.Web" />
            <add namespace="System.Web.Helpers" />
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Web.WebPages" />
            <add namespace="MyMainSite2.Library.Extensions" />
        </namespaces>
    </pages>
</system.web>
Run Code Online (Sandbox Code Playgroud)

扩展方法代码:

namespace MyMainSite2.Library.Extensions
{
    public static class UriExtensions
    {
        #region Public Static Methods

        public static bool IsCurrentUrl(this Uri uri, string url)
        {
            if (String.IsNullOrWhiteSpace(url))
                return false;

            url = url.Trim().ToLower();
            string absolutePath = uri.AbsolutePath.Trim().ToLower();

            if (!url.StartsWith("/") && absolutePath.StartsWith("/"))
                absolutePath = absolutePath.Remove(0, 1);

            bool match = absolutePath == url;

            return match;
        }

        #endregion
    }
}
Run Code Online (Sandbox Code Playgroud)

剃刀代码:

@model MyMainSite2.UI.Web.Models.Shared.TopMenuModel

@foreach (var item in this.Model.Items)
{
    if(this.Request.Url.IsCurrentUrl(item.Url)) // this line is failing because UriExtensions.IsCurrentUrl is not being found
    {
        @:<li class="current">
    }
    else
    {
        @:<li>
    }

    @:<a href="@item.Url">@item.Text</a></li>
}
Run Code Online (Sandbox Code Playgroud)

rhu*_*hes 23

答案是由petro.sidlovskyy给出的.

我将命名空间添加到主Web.config而不是视图的Web.config.

当我添加了命名空间的视图文件夹中的Web.config,命名空间是由视图识别,从而解决了问题.