26 Mayıs 2010 Çarşamba

Dynamic sitemap in ASP.NET MVC

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MVCUrlAttribute : ActionFilterAttribute
{
public string Url { get; private set; }

public MVCUrlAttribute(string url)
{
this.Url = url;
}

public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// Put this 'canonical url' into the model (which feeds the view)
// to help search engines with issues of duplicate content
filterContext.Controller.ViewData["CanonicalUrl"] = url;
base.OnResultExecuting(filterContext);
}
}


// Find all the MVC Routes
Log.Debug("*** FINDING ALL MVC ROUTES MARKED FOR INCLUSION IN SITEMAP");
var allControllers
= Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(typeof(Controller)));
Log.DebugFormat(
"Found {0} controllers", allControllers.Count());

foreach (var controllerType in allControllers)
{
var allPublicMethodsOnController
= controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
Log.DebugFormat(
"Found {0} public methods on {1}", allPublicMethodsOnController.Count(), controllerType.Name);

foreach (var publicMethod in allPublicMethodsOnController)
{
var mvcurlattr
= publicMethod.GetCustomAttributes(true).OfType<MVCUrlAttribute>().FirstOrDefault();
if (mvcurlattr != null)
{
string url = mvcurlattr.Url;
Log.Debug(
"Found " + controllerType.Name + "." + publicMethod.Name + " <-- " + url);
Global.SiteMapUrls.Add(url);
//<-- your code here using url
}
}
}


 



 



 




protected string GetUrl(object routeValues)
{
RouteValueDictionary values
= new RouteValueDictionary(routeValues);
RequestContext context
= new RequestContext(HttpContext, RouteData);

string url = RouteTable.Routes.GetVirtualPath(context, values).VirtualPath;

return new Uri(Request.Url, url).AbsoluteUri;
}

List
<string> urlList = new List<string>();
urlList.Add(GetUrl(
new { controller = "Help", action = "Edit" }));
urlList.Add(GetUrl(
new { controller = "Help", action = "Create" }));
urlList.Add(GetUrl(
new { controller = "About", action = "Company" }));
urlList.Add(GetUrl(
new { controller = "About", action = "Management" }));

Hiç yorum yok:

Yorum Gönderme