asp.net mvc 实现类似园子里面的伪静态,附带多个参数


思路:
检查被请求的路径,以确定 URL 是否需要重写。
如果需要重写,通过调用 RewritePath() 方法来重写路径。

其实我的最终目的就是实现一个 类似 : http://mobile.9om.com/138745/13874585123.html 这种效果

网上找了许多资料,仍然无法完成 , 希望大神给予帮助,最好能有个demo

首先我为了实现伪静态 把 : asp.net 生命周期 理清晰 地址 :主要看的是 张子阳的这三篇博客
http://www.cnblogs.com/JimmyZhang/archive/2007/09/04/880967.html
http://www.cnblogs.com/JimmyZhang/archive/2007/09/15/894124.html
http://www.cnblogs.com/JimmyZhang/archive/2007/11/25/971878.html

其次自己动手试着实现了这些功能 , 最后准备 用 system.web.routing 来实现 (cshtml) 伪静态 (以 html为后缀 )

就拿前面三个链接的第一个来说把

上面的实际地址我用 mvc 还原大概是 http://www.cnblogs.com/blog/archive?name=JimmyZhang &year=2007&month=09&day=04&id=880967 ( 这里不是 以 .aspx 后缀的view 噢 , 我用的是 cshtml 哦)
我最终想实现的效果就是 这种效果 http://www.cnblogs.com/JimmyZhang/archive/2007/09/04/880967.html

下面是我查询得一些 资料 基本上是以 aspx为例子:
https://msdn.microsoft.com/zh-cn/library/ms972974.aspx#XSLTsection123121120120

http://www.cnblogs.com/chsword/archive/2008/08/27/system_web_routing_1.html

以及我自己写的东西:

重写了 IHttpHandler

public class HtmHandler : IHttpHandler
{


 public RequestContext RequestContext { get; private set; }
  public HtmHandler(RequestContext context)
  {
     this.RequestContext = context;
  }
  #region IHttpHandler 成员
  public virtual void ProcessRequest(HttpContext context)
  {
 context.Server.Execute(RequestContext.RouteData.Values["html"].ToString().Replace("-", "/"));
   //RequestContext.RewritePath(path, Urls, query, true);

}


 public bool IsReusable {
   get { return true; }

}

#endregion

重写了IRouteHandler
*public class MyRouteHandler : IRouteHandler
{

region IRouteHandler 成员

public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
HtmHandler.HtmHandler html=new HtmHandler.HtmHandler(requestContext);
return html;
}

endregion

}*
图片描述

我想过这样去调用,可以分成 Controller 和 Action 可是仍然报错

下面是我自己实现的一个简单示例,但是仍然没有达到我的效果( http://mobile.9om.com/138745/13874585123.html 这种效果)

在没有办法的情况下用了这个方法 :

这里是我的路由代码:
routes.MapRoute(


 name: "Default1",
          url: "phone/{phone}.html",
          defaults: new { controller = "about", action = "Index", phone =                                       UrlParameter.Optional }

);
这里是 Controller 中的 action
public ActionResult Index(string phoneName)
{


 // string phone = Request.Form["phone"];
  if (string.IsNullOrEmpty(phoneName))
  {
     ViewBag.phone = 1;
   }
   else
    {
       ViewBag.phone = phoneName;
    }

return View();
}


 <form method="POST" action="@Url.Action("index", "about", new { phone =   ViewBag.phone })">
 <input id="textbox" type="text" name="phoneName" />
 <input type="submit" value="submit" />
 <a href="#">submit</a>
</form>

图片描述

结果 : 参数传递与地址栏显示没有同步 , 地址栏中的显示慢了半拍(就是晚了一步,还是失败告终)

最后附上 web.config

<system.webServer>


 <modules>
  <remove name="FormsAuthenticationModule" />
</modules>
<handlers>
  <add name="urlRoute" path="*.html" verb="*" type="HtmHandler.HtmHandler,HtmHandler"/>
</handlers>

</system.webServer>

system.web.routing 伪静态 asp.net-mvc asp.net

漆黑之牙约修亚 8 years, 11 months ago

Your Answer