我有这样的问题。在RouteConfig.cs中,我设置了路径
routes.MapRoute(
"NewsDetails",
"news/details-news/{title}-{id}",
new { controller = "News", action = "Details", id = "", title = "" }
);
在NewsController的Index.cshtml中,我有一个链接
@Html.RouteLink(item.Title, "NewsDetails", new {
title = MyWeb.Classes.PrettyUrlHelper.PrettyUrl(item.Title),
id = item.Id
})
在我的NewsController中:
public ActionResult Details(string title,String id)
{
if (id == null && title == null)
return RedirectToAction("Index");
try
{
int ID = Int32.Parse(id);
var result = NewsConnectionDB.GetInstance().Single<LifeStory>(ID);
return View(result);
}
catch (InvalidOperationException) {
return View("~/Views/Error/Error404.cshtml");
}
catch (FormatException) {
return View("~/Views/Error/Error404.cshtml"); }
}
因此,如果用户点击View中的链接,该链接将路由到要处理的操作详细信息,并且该链接是Seo Url Friendly(localhost:9224 / news / details-news / ten-things-2)。但是用户键入链接而不是单击View中的链接:
localhost:9224/news/details-news/ten-thingsblahblahblah-2
上面的url是正确的id但标题不是。那么如果用户输入错误的标题但是正确的ID,我如何在返回View后更新网址?
任何帮助都将不胜感激。
P / S:我的英语不好,所以我希望你能理解。答案 0 :(得分:0)
如果标题不正确,那么您可以在响应标头中发送正确的网址。如果它是ajax调用,则在完成时检查响应头中的正确url。如果存在正确的网址,请使用window.history.pushState
javascript方法更改您的浏览器网址。
在详细信息操作方法中,使用以下代码设置响应标头。
HttpContext.Current.Response.AppendHeader("CorrectUrl", "YourUrl");
答案 1 :(得分:0)
使用 HttpServerUtility.UrlEncode(字符串);
javascript代码可以替换url,我认为它会工作:)。
C#代码
string _entitle = HttpServerUtility.UrlEncode(_strTitle);
string _strCorUrl = "http://example.com/"+ _entitle + "-" + _intID.toString();
脚本代码
top.window.location.replace('CorrectUrl');
或C#代码重定向网址
Response.Redirect(url);
<强>更新强> 使用 Context.RewritePath
的可能的解决方案https://msdn.microsoft.com/en-us/library/sa5wkk6d(v=vs.110).aspx
void Application_BeginRequest(Object sender, EventArgs e)
{
string originalPath = HttpContext.Current.Request.Path.ToLower();
if (originalPath.Contains("/page1"))
{
Context.RewritePath(originalPath.Replace("/page1", "/RewritePath.aspx?page=page1"));
}
if (originalPath.Contains("/page2"))
{
Context.RewritePath(originalPath.Replace("/page2", "/RewritePath.aspx"), "pathinfo", "page=page2");
}
}
代码是示例,您可以使用它 我希望它有所帮助