ASP.NET 路由实现去除aspx后缀

源码下载

引用dll(DownLoad

DotNetOpenAuth.Core.dll

Microsoft.AspNet.FriendlyUrls.dll

Microsoft.AspNet.Membership.OpenAuth.dll


Web.Config加入配置

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <!--# ASP.NET 实现去掉aspx后缀 #-->
        <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" />
        <!--# ASP.NET 实现去掉aspx后缀 #-->
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
<!--ProjectGuid: 5ACDD4E8-3966-4E26-9538-B62996B5E60F-->

Global.asax加入配置

protected void Application_Start(object sender, EventArgs e)
{
    /*# ASP.NET 实现去掉aspx后缀 #*/
        //扩展自定义路由
     //var defaults = new RouteValueDictionary { { "name", "*" }, { "id", "*" } };
     //RouteTable.Routes.MapPageRoute("", "employees/{name}/{id}", "~/EmployeePage.aspx", true, defaults);//defaults可为null
        
     //页面中读取路由值
     //string name = Page.RouteData.Values["name"].ToString()
     //string id = Page.RouteData.Values["id"].ToString()  
  
        RouteConfig.RegisterRoutes(RouteTable.Routes);//官方aspx路由规则
    /*# ASP.NET 实现去掉aspx后缀 #*/
}

新建RouteConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/*# ASP.NET 实现去掉aspx后缀 #*/
using Microsoft.AspNet.Membership.OpenAuth;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
/*# ASP.NET 实现去掉aspx后缀 #*/

namespace AuthStore
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.EnableFriendlyUrls();
        }
    }
}

ASP.NET 扩展=>去除asmx后缀

protected void Application_BeginRequest(object sender, EventArgs e)
{
    /*# ASP.NET 实现去除asmx后缀 #*/
    if (Request.Url.LocalPath.Contains(".asmx"))
        this.MapPageRoute("/api/apiCenter", "/api/apiCenter.asmx");
    /*# ASP.NET 实现去除asmx后缀 #*/
}

/*
 * Web.Config加入(禁止直接访问asmx,只允许Post、Get、Soap请求asmx)
   <system.web>
    <webServices>
      <protocols>
        <add name="HttpSoap"/>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
      <wsdlHelpGenerator href="拒绝访问.aspx"/>
    </webServices>
  </system.web>
 */

/// <summary>
/// URL重写(区分大小写)
/// </summary>
/// <param name="VirtualPath">虚拟路径(区分大小写)</param>
/// <param name="RealPath">真实路径(区分大小写)</param>
private void MapPageRoute(string VirtualPath, string RealPath)
{
    string LocalPath = Request.Url.LocalPath;

    if (!LocalPath.Contains(RealPath))
    {
        if (LocalPath.Contains(VirtualPath))
        {
            Context.RewritePath(LocalPath.Replace(VirtualPath, RealPath));
        }
    }
}


猜你喜欢

转载自blog.csdn.net/qq285679784/article/details/78350782