开发者

ASP.NET MVC Site Map Provider Breaks Under Heavy Load

I have an issue with the ASP.NET MVC Site Map provider and it is causing alot of headaches for me.开发者_运维知识库 The issue comes when the server is under heavy load the URL is resolved incorrectly. I have just upgraded to the latest version (3.1.0 RC) where i hoped this would be fixed but unfortunately it hasn't.

I tried to produce a local test to verify this but i was unable to replicate the load on the server. Therefore i will show you a unit test i fire against the live server:

[TestMethod]
public void ForumTopic_Breadcrumb() {
    // Arrange
    var isValid = true;

    for (var i = 0; i < 100; i++) {
        try {
            // Send the request
            var request = Http.WebRequest("http://www.mysite.com/Forum/ViewTopic/38044"); // Http.WebRequest is a utility method to send a request to the server and retrieve the content (Note: now the question has been answered i have remove the reference to the actual site)

            // Parse the html document
            var document = new HtmlDocument(); // HTML Agility Pack
            document.LoadHtml(request.Data);

            // Get the required info
            var forumNode = document.DocumentNode.SelectSingleNode("//div[@id='breadcrumb']/a[@href='/Forum/ViewForum/1']");
            var topicNode = document.DocumentNode.SelectSingleNode("//div[@id='breadcrumb']/span");

            // Test if the info is valid
            if (forumNode == null || topicNode.InnerText != "Test Topic")
                throw new Exception();
        } catch {
            isValid = false;
            break;
        }
    }

    // Asset
    Assert.IsTrue(isValid);
}

This test fails as often the wrong breadcrumb and/or title is displayed.

My ViewTopic action method has the following code in it:

// Override the parent node title and url
SiteMap.CurrentNode.ParentNode.Title = topic.Forum.ForumName;
SiteMap.CurrentNode.ParentNode.Url = Url.GenerateUrl("ViewForum", new { id = topic.Forum.ForumID });

// Set the meta description
SiteMap.CurrentNode["MetaDescription"] = topic.Subject;

Aswell as having the SiteMapTitle attribute applied to change the current nodes title to the subject of the topic.

I'd really appreciate it if you could help. Thanks


I've received a response from the developer saying that this is due to a limitation with ASP.NET. He hopes to remove this in version 4 by completely segregating out this functionality. Until then the best solution is to override the title by passing it as ViewData.

Edit (below is the temporary solution i have come up with):

Create the following SiteMapAttribute.cs file:

public class SiteMapAttribute : ActionFilterAttribute {
    protected string TitlePropertyName { get; set; }
    protected string PageTitlePropertyName { get; set; }
    protected string MetaDescriptionPropertyName { get; set; }
    protected string MetaKeywordsPropertyName { get; set; }
    protected string ParentTitlePropertyName { get; set; }

    public SiteMapAttribute() {
    }

    public SiteMapAttribute(string titlePropertyName) {
        TitlePropertyName = titlePropertyName;
    }

    public SiteMapAttribute(string titlePropertyName, string pageTitlePropertyName, string metaDescriptionPropertyName, string metaKeywordsPropertyName)
        : this(titlePropertyName) {
        PageTitlePropertyName = pageTitlePropertyName;
        MetaDescriptionPropertyName = metaDescriptionPropertyName;
        MetaKeywordsPropertyName = metaKeywordsPropertyName;
    }

    public SiteMapAttribute(string titlePropertyName, string pageTitlePropertyName, string metaDescriptionPropertyName, string metaKeywordsPropertyName, string parentTitlePropertyName)
        : this(titlePropertyName, pageTitlePropertyName, metaDescriptionPropertyName, metaKeywordsPropertyName) {
        ParentTitlePropertyName = parentTitlePropertyName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext) {
        if (filterContext.Result is ViewResult) {
            var result = (ViewResult)filterContext.Result;

            // Get the current node
            var currentNode = filterContext.Controller.GetCurrentSiteMapNode();

            // Make sure the node is found
            if (currentNode != null) {
                // Set the title and meta information (if applicable)
                if (!result.ViewData.ContainsKey("Title"))
                    result.ViewData["Title"] = Resolve(result, TitlePropertyName) ?? currentNode.Title;

                if (!result.ViewData.ContainsKey("PageTitle"))
                    result.ViewData["PageTitle"] = Resolve(result, PageTitlePropertyName) ?? (currentNode["PageTitle"] ?? currentNode.Title);

                if (!result.ViewData.ContainsKey("MetaDescription"))
                    result.ViewData["MetaDescription"] = Resolve(result, MetaDescriptionPropertyName) ?? currentNode["MetaDescription"];

                if (!result.ViewData.ContainsKey("MetaKeywords"))
                    result.ViewData["MetaKeywords"] = Resolve(result, MetaKeywordsPropertyName) ?? currentNode["MetaKeywords"];

                if (!result.ViewData.ContainsKey("ParentTitle"))
                    result.ViewData["ParentTitle"] = Resolve(result, ParentTitlePropertyName);
            }
        }
    }

    private string Resolve(ViewResult result, string propertyName) {
        if (string.IsNullOrEmpty(propertyName))
            return null;

        var target = ResolveTarget(result.ViewData.Model, propertyName);

        if (target == null)
            target = ResolveTarget(result.ViewData, propertyName);

        return target != null ? target.ToString() : null;
    }

    private object ResolveTarget(object target, string expression) {
        try {
            var parameter = Expression.Parameter(target.GetType(), "target");
            var lambdaExpression = DynamicExpression.ParseLambda(new[] { parameter }, null, "target." + expression);
            return lambdaExpression.Compile().DynamicInvoke(target);
        } catch {
            return null;
        }
    }
}

You then need to make sure all of your controllers have this attribute applied. In ASP.NET MVC 3 this is alot simpler as you can register this as a global filter.

Now you need to modify the your master page and say something like:

<head>
    <title><%= ViewData["PageTitle"] %></title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <% if (ViewData["MetaDescription"] != null && !string.IsNullOrEmpty(ViewData["MetaDescription"].ToString())) { %>
        <meta name="Description" content="<%= ViewData["MetaDescription"] %>" />
    <% } %>
    <% if (ViewData["MetaKeywords"] != null && !string.IsNullOrEmpty(ViewData["MetaKeywords"].ToString())) { %>
        <meta name="Keywords" content="<%= ViewData["MetaKeywords"] %>" />
    <% } %>
</head>

Now to patch the breadcrumb (SiteMapPath) i had to get a little hacky. First i created my own helper:

/// <summary>
/// MvcSiteMapHtmlHelper extension methods
/// </summary>
public static class SiteMapBreadcrumbExtensions {
    /// <summary>
    /// Source metadata
    /// </summary>
    private static Dictionary<string, object> SourceMetadata = new Dictionary<string, object> { { "HtmlHelper", typeof(SiteMapBreadcrumbExtensions).FullName } };

    /// <summary>
    /// Gets SiteMap path for the current request
    /// </summary>
    /// <param name="helper">MvcSiteMapHtmlHelper instance</param>
    /// <returns>SiteMap path for the current request</returns>
    public static MvcHtmlString SiteMapBreadcrumb(this MvcSiteMapHtmlHelper helper) {
        return SiteMapBreadcrumb(helper, null);
    }

    /// <summary>
    /// Gets SiteMap path for the current request
    /// </summary>
    /// <param name="helper">MvcSiteMapHtmlHelper instance</param>
    /// <param name="templateName">Name of the template.</param>
    /// <returns>SiteMap path for the current request</returns>
    public static MvcHtmlString SiteMapBreadcrumb(this MvcSiteMapHtmlHelper helper, string templateName) {
        var model = BuildModel(helper, helper.Provider.CurrentNode);

        return helper
            .CreateHtmlHelperForModel(model)
            .DisplayFor(m => model, templateName, new { Title = helper.HtmlHelper.ViewData["Title"], ParentTitle = helper.HtmlHelper.ViewData["ParentTitle"], ParentUrl = helper.HtmlHelper.ViewData["ParentUrl"] });
    }

    /// <summary>
    /// Builds the model.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="startingNode">The starting node.</param>
    /// <returns>The model.</returns>
    private static SiteMapPathHelperModel BuildModel(MvcSiteMapHtmlHelper helper, SiteMapNode startingNode) {
        // Build model
        var model = new SiteMapPathHelperModel();
        var node = startingNode;

        while (node != null) {
            var mvcNode = node as MvcSiteMapNode;

            // Check visibility
            var nodeVisible = true;

            if (mvcNode != null)
                nodeVisible = mvcNode.VisibilityProvider.IsVisible(node, HttpContext.Current, SourceMetadata);

            // Check ACL
            if (nodeVisible && node.IsAccessibleToUser(HttpContext.Current))
                model.Nodes.Add(SiteMapNodeModelMapper.MapToSiteMapNodeModel(node, mvcNode, SourceMetadata));

            node = node.ParentNode;
        }

        model.Nodes.Reverse();

        return model;
    }
}

The only difference between this and the built in one is that it passes the ViewData to the template. Then finally i created 2 DisplayTemplates:

SiteMapNodeModel.axcx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcSiteMapProvider.Web.Html.Models.SiteMapNodeModel>" %>
<% if (Model.IsCurrentNode) { %>
    <span class="orange-text"><%= (ViewData["Title"] ?? Model.Title).ToString() %></span>
<% } else if ((bool)ViewData["IsParent"]) { %>
    <a href="<%= (ViewData["ParentUrl"] ?? Model.Url).ToString() %>"><%= (ViewData["ParentTitle"] ?? Model.Title).ToString() %></a>
<% } else { %>
    <a href="<%= Model.Url %>"><%= Model.Title %></a>
<% } %>

And SiteMapPathHelperModel.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcSiteMapProvider.Web.Html.Models.SiteMapPathHelperModel>" %>
<% for (var i = 0; i < Model.Nodes.Count(); i++) { %>
    <%= Html.DisplayFor(m => Model.Nodes[i], new { isParent = Model.Count() - 2 == i }) %>
    <% if (Model.Nodes[i] != Model.Last()) { %>
        &gt;
    <% } %>
<% } %>

You can now say the following within your view to display the overridden breadcrumb:

<%= Html.MvcSiteMap().SiteMapBreadcrumb() %>

With that done now you just need to know how to override the meta/breadcrumb information for a particular action. The easiest way to do this is to override the SiteMapAttribute for a particular action e.g.

[SiteMap("Subject", "Subject", "Subject", "", "Forum.ForumName")]
public ActionResult ViewTopic(int id, [DefaultValue(1)] int page) {
}

This will set the title, page title, meta information and parent title accordingly. If you would like the title bound to something more complicated than a single property you could set this within the action method by saying something like:

ViewData["Title"] = "My Title - " + DateTime.UtcNow.ToShortDateString();

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜