[英]asp.net mvc - Rewrite Url after return view
我有这样的问题。 在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"); }
}
因此,如果用户单击“视图”中的链接,则该链接将转至要处理的操作“详细信息”,并且该链接是Seo Url友好的(localhost:9224 / news / details-news / ten-things-2)。 但是用户键入链接而不是单击“视图”中的链接:
localhost:9224/news/details-news/ten-thingsblahblahblah-2
上面的网址使用ID正确,但标题不正确。 因此,如果用户键入了错误的标题但输入了正确的ID,如何在返回View后更新URL?
任何帮助,将不胜感激。
P / S:我的英语不好,所以我希望你能理解。
如果标题不正确,则可以在响应标题中发送正确的url。 如果是ajax调用,则在完成时检查响应头中的URL是否正确。 如果存在正确的网址,请使用window.history.pushState
javascript方法更改浏览器的网址。
在“ 详细信息”操作方法中,使用以下代码设置响应头。
HttpContext.Current.Response.AppendHeader("CorrectUrl", "YourUrl");
使用HttpServerUtility.UrlEncode(string);
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 更新可能的1解决方案
https://msdn.microsoft.com/zh-CN/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");
}
}
它是示例代码,可以使用,希望对您有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.