Storing links to internal content pages in ASP.NET MVC
I'm using a route like this
routes.MapRoute(
"PageBySlug",
RouteType.Regular,
"{slug}",
new {controller = "Page", action = "Display", slug = "Default"}, null
);
to map request to ~/Some-Page-Slug to ~/Page/Display/Some-Page-Slug.
When adding content, user can choose to link to existing pages to create references and I then store those links in this format in the datastore: "/Some-Page-Slug".
When I run the app in Cassini and pull the link out from datastore and attach it to A tag it looks like this http://localhost:93229/Some-Page-Slug and this link works.
But when running the application in virtual directory under some website in IIS, the attached link generates this URL http://localhost/Some-Page-Slug, when it should be http://localhost/virtualdir/Some-Page-Slu开发者_StackOverflow社区g.
Of course, this generates 404 error.
How can I solve this to be universally useful and working under all circumstances? Should I store it differently in the database or should I transform it into correct form in my Views at runtime and how to do that?
I've found one solution already:
RouteValueDictionary routeValues = new RouteValueDictionary
{
{"slug", Html.Encode(Model.Url)}
};
// the commented lines work in IIS but not is ASP.NET builtin server
//string url = UrlHelper.GenerateUrl("PageBySlug", "Display", "Page", routeValues, RouteTable.Routes,
//Request.RequestContext, true);
string url = Url.Content("~/" + Html.Encode(Model.Url)); // this works in both
If you have other suggestions, they're welcome!
精彩评论