ASP.NET Web API 框架研商  ASP.NET 路由

ASP.NET Web API 框架研商 ASP.NET 路由

一、前台控件使用路由,通过表明式生成url地址,注意给路由参数赋值,幸免利用了其他路由表明式值
方式1:
<asp:HyperLink ID=”hlSupply” NavigateUrl='<%$RouteUrl:routename=TechSupplySearch,areacode=,techfield=%>’
runat=”server”>本事须要</asp:HyperLink>
方式2:
<a href=”<%=GetRouteUrl(“MemberSearch”,new {
membertype=”Commpany” ,areacode=””,industrycode=””,pageindex=”” })
%>”>科学和技术公司</a>

  {

    //ItemCreated事件
    protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
           //判定Button是还是不是留存
            if (e.Item.FindControl(“Button1”) != null)
            {
               //假使存在,把对象调换为Button。
                Button InsusButton = (Button)e.Item.FindControl(“Button1”);
                //产生Click事件
                InsusButton.Click += new EventHandler(InsusButton_Click);
            }
        }
    }

澳门新萄京 1澳门新萄京 2View Code

//注册路由
routes.MapPageRoute(“TechNewsSearch”,
“TechNews/{pageindex}”, “~/NewsInfo/TechNewsSearch.aspx”, true, new
RouteValueDictionary { { “pageindex”, “1” } }, new RouteValueDictionary
{ { “pageindex”, @”\d{1,}” } });

    private sealed class IgnoreRouteInternal : Route
    {
      public
IgnoreRouteInternal(string url)
        : base(url, (IRouteHandler)new StopRoutingHandler())
      {
      }

如何得到Repeater控件主键,Repeater控件未有如Gridview的DataKeyNames属性。想获得Repeater记录的主键只有另想办法了。

 

Page.RouteData.Values.Remove; //移除路由参数

    //约束,正则表明式
    var constaints = new RouteValueDictionary { { “areacode”, @”0\d{2,3}” }, { “days”, @”[1-3]” } };

.aspx(注重部分已经有注释):

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
           //Insus.NET: 推断Literal控件是还是不是留存,若无写此推断,程式有非常的大只怕在找不到时抛出特别
            if (e.Row.FindControl(“Literal1”) != null)
            {
                //Insus.NET:找到了,把对象转为控件。
                Literal literal = (Literal)e.Row.FindControl(“Literal1”);

//routes.Ignore(“{resource}.axd/{*pathinfo}”);//经实行这种方法屏蔽对静态财富文件的路由无效。
//routes.Ignore(“{path}/{name}.jpg”);//经施行这种格局屏蔽对静态能源文件的路由无效。

  public class VirtualPathData
  {
    private RouteValueDictionary _dataTokens = new RouteValueDictionary();
    private string
_virtualPath;

 

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “;
<html xmlns=”;
<head runat=”server”>
    <title></title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
    </asp:ScriptManager>
    <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
        <ContentTemplate>
            <div>
                <asp:Button ID=”ButtonSingleSelect” runat=”server” Text=”GetGridViewRasioSelectedValue” OnClick=”ButtonSingleSelect_Click” />
                <p />
                <!–Insus.NET:GridView有贰个事变OnRowDataBound –>
                <asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”false” OnRowDataBound=”GridView1_RowDataBound”>
                    <Columns>
                        <asp:TemplateField HeaderText=”选择”>
                            <HeaderStyle BorderWidth=”1″ BorderColor=”#c0c0c0″ />
                            <ItemStyle BorderWidth=”1″ BorderColor=”#c0c0c0″ />
                            <ItemTemplate>
                               <!–Insus.NET:这里是重大多数,使用Literal控件装载HtmlInputRadioButton –>
                                <asp:Literal ID=”Literal1″ runat=”server”></asp:Literal>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText=”ID”>
                            <HeaderStyle BorderWidth=”1″ BorderColor=”#c0c0c0″ />
                            <ItemStyle BorderWidth=”1″ BorderColor=”#c0c0c0″ />
                            <ItemTemplate>
                                <%# Eval(“MemberId”) %>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText=”Name”>
                            <HeaderStyle BorderWidth=”1″ BorderColor=”#c0c0c0″ />
                            <ItemStyle BorderWidth=”1″ BorderColor=”#c0c0c0″ />
                            <ItemTemplate>
                                <%# Eval(“Name”) %>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText=”Email”>
                            <HeaderStyle BorderWidth=”1″ BorderColor=”#c0c0c0″ />
                            <ItemStyle BorderWidth=”1″ BorderColor=”#c0c0c0″ />
                            <ItemTemplate>
                                <%# Eval(“Email”) %>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>

控件分界面数据绑定中选取
<asp:Repeater ID=”myGrid” ViewStateMode=”Disabled”
runat=”server”>
<ItemTemplate>
<li><a target=”_blank” href='<%# this.GetRouteUrl(“TechSupplyView”, new {
id=Eval(“SupplyId”)}) %>’ ><%#
Eval(“SupplyName”)%></a><span><%#
string.IsNullOrEmpty(Eval(“cityname”).ToString ? “&nbsp” :
Eval(“cityname”)%></span><span><%#
Eval(“hightech”)%></span> </li>
</ItemTemplate>
</asp:Repeater>

    //管理约束
    protected virtual bool ProcessConstraint(HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection
      routeDirection)
    {
      IRouteConstraint
routeConstraint = constraint as
IRouteConstraint;
      if (routeConstraint !=
null)
        return
routeConstraint.Match(httpContext, this, parameterName, values,
routeDirection);
      string str = constraint
as string;
      if (str == null)
        throw new InvalidOperationException(string.Format((IFormatProvider)CultureInfo.CurrentUICulture,
                            System.Web.SR.GetString(“Route_ValidationMustBeStringOrCustomConstraint”),
new object[2]
      {
        (object)
parameterName,
        (object) this.Url
      }));
      object obj;
      values.TryGetValue(parameterName, out obj);
      return Regex.IsMatch(Convert.ToString(obj, (IFormatProvider)CultureInfo.InvariantCulture), “^(” + str + “)$”, RegexOptions.IgnoreCase |
              RegexOptions.CultureInvariant);
    }

 

                //Insus.NET: 把HtmlInputRadioButton绑定至Literal控件上。
                literal.Text = “<input id=\”InsusRadio1\” type=\”radio\” name=\”InsusRadio1\” value=\”” + value + “\” />”;
            }
        }
    }
}

后台代码中生成路由地点
newUrl = this.GetRouteUrl(“MemberSearch”,
Page.RouteData.Values);

  RouteCollection和RouteBase都有品质RouteExistingFiles ,默许值分别为
false和true,要学有所成相配路由,要满意五个原则

上边那一个例子,是在每笔记录行放叁个Button(当然用LinkButton也可),客商点一点以此铵钮,就能够获得那些记录。

 

二、服务端后台代码应用路由

    //路由模板,如/weather/{areacode}/{days},须求的U卡宴L就是跟该模板实行相称,/分割成多少个段,每一种段又分变量(areacode,days)和字面量(weather)

public partial class Default2 : System.Web.UI.Page
{
    Member objMember = new Member();
    InsusJsUtility objJs = new InsusJsUtility();

 

1、Global.asax文件:
void Application_Start(object sender, EventArgs e)
{
//在应用程序运行时运转的代码
RegisterRoutes(RouteTable.Routes);
}
//注册url路由
void RegisterRoutes(RouteCollection
routes)
{
routes.RouteExistingFiles = false; //暗许不路由与物理路线一致的url:如

  var recipes =
    new RecipeRepository()
      .GetAllRecipeNames()
      .OrderBy(recipeName => recipeName)
      .Select(recipeName =>
        new
        {
          Name = recipeName,
          Url = GetVirtualPathForRecipe(recipeName)
        });

 

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

routes.MapPageRoute(“TechSupplySearch”,
“Supply/{areacode}/{techfield}/{pageindex}”,
“~/TechSupply/TechSupplySearch.aspx”, true, new RouteValueDictionary { {
“areacode”, “0” }, { “techfield”, “0” }, { “pageindex”, “1” } }, new
RouteValueDictionary { { “pageindex”, @”\d{1,}” } });

    private class ReadLockDisposable : IDisposable
    {
      private ReaderWriterLockSlim _rwLock;

    private void Data_Binding()
    {
        this.Repeater1.DataSource = objMember.GetMember().Tables[0];
        this.Repeater1.DataBind();
    }

        public DataTable GetMember()
        {
            return objBusinessBase.GetDataToDataSet(“usp_GetMember”).Tables[0];
        }
    }
}

获取、改造路由参数值
routeValue = Page.RouteData.Values[“techfield”] == null ? string.Empty
: Page.RouteData.Values[“techfield”].ToString();//获取路由参数

  全局路由表,即RouteTable类的静态属性Routes
类型为RouteCollection,通过内部的MapPageRoute方法开展路由映射

}

 

页面顾客端跳转路由艺术完毕
Response.RedirectToRoute(“TechSupplySearch”, Page.RouteData.Values);
Response.RedirectToRoutePermanent(“TechSupplySearch”,
Page.RouteData.Values);

    private bool
IsRouteToExistingFile(HttpContextBase httpContext)
    {
      string executionFilePath
= httpContext.Request.AppRelativeCurrentExecutionFilePath;
      if (!(executionFilePath
!= “~/”) || this.VPP == null)
        return false;
      if (!this.VPP.FileExists(executionFilePath))
        return
this.VPP.DirectoryExists(executionFilePath);
      return true;
    }

澳门新萄京 3澳门新萄京 4View Code

直白很想写一个Gridview内完毕单选功效,不过一贯未曾太多日子,近段时间三个网民问及此功用,只能抽取些少时间来兑现,上面为贯彻进程。

url 路由分页控件:urlpager

  public interface IRouteConstraint
  {
    bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection);
  }

选择结果:

/// <summary>
/// Summary description for Member
/// </summary>
namespace Insus.NET
{
    public class Member
    {
        BusinessBase objBusinessBase = new BusinessBase();

2、WebForm页面后台代码中动用

3、直接路由物理文件(RouteExistingFiles)

澳门新萄京 5澳门新萄京 6View Code

存过程:

Page.RouteData.Values[“areacode”] = selOrgan.SelectedValue;//所在地
退换路由参数

    protected override void
InsertItem(int index, RouteBase item)
    {
      if (item == null)
        throw new ArgumentNullException(nameof(item));
      if (this.Contains(item))
        throw new ArgumentException(string.Format((IFormatProvider)CultureInfo.CurrentCulture,
System.Web.SR.GetString(“RouteCollection_DuplicateEntry”), new           object[0]),
nameof(item));
      base.InsertItem(index,
item);
    }

澳门新萄京 7

澳门新萄京 8

routes.MapPageRoute(“MemberSearch”,
“Members/{membertype}/{areacode}/{industrycode}/{pageindex}”,
“~/Member/MemberSearch.aspx”, true, new RouteValueDictionary { {
“membertype”, “0” }, { “areacode”, “0” }, { “industrycode”, “0” }, {
“pageindex”, “1” } }, new RouteValueDictionary { { “pageindex”,
@”\d{1,}” } });
}

  RouteTable.Routes.Add(new Route(“{areacode}/{days}”,defaults, constaints,
dataTokens,new PageRouteHandler(“~/my.aspx”, false ));

   <!–手艺首假设应用OnItemCreated,实际不是利用OnItemDataBound–>
                <asp:Repeater ID=”Repeater1″ runat=”server” OnItemCreated=”Repeater1_ItemCreated”>
                    <HeaderTemplate>
                        <table border=”1″ cellpadding=”5″ cellspacing=”0″ width=”100%”>
                            <tr>
                                <td>
                                    ID
                                </td>
                                <td>
                                    Name
                                </td>
                                <td>
                                    Email
                                </td>
                                <td>
                                    SELECT
                                </td>
                            </tr>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <tr>
                            <td>
                                <%# Eval(“MemberId”) %>
                                <!–由于Repeater控件未有如GridView的DataKeyNames属性,因而放二个HiddenField控件–>
                                <asp:HiddenField ID=”HiddenField1″ runat=”server” Value='<%# Eval(“MemberId”) %>’ />
                            </td>
                            <td>
                                <%# Eval(“Name”) %>
                            </td>
                            <td>
                                <%# Eval(“Email”) %>
                            </td>
                            <td>
                                <!–只放贰个Button,没有要求写什么,当然你拉贰个LinkButton也足以–>
                                <asp:Button ID=”Button1″ runat=”server” Text=”Button” />
                            </td>
                        </tr>
                    </ItemTemplate>
                    <FooterTemplate>
                        </table>
                    </FooterTemplate>
                </asp:Repeater>

GridviewSingleSelection.aspx.cs:

asp.net web form 使用UENVISIONL路由
注不是mvc中的路由

  其余,RequestContext是对Http央浼上下文和路由数据的卷入

.aspx.cs:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”GridviewSingleSelection.aspx.cs”
    Inherits=”GridviewSingleSelection” %>

    public void Add(string name, RouteBase item)
    {
      //…
      this.Add(item);
      if (!string.IsNullOrEmpty(name))
        this._namedMap[name] = item;
      Route route = item as
Route;
      if (route == null || route.RouteHandler == null)
        return;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Data_Binding();
        }
    }

Member.cs 类别:

 

    //怎样获取主键
    private void InsusButton_Click(object sender, EventArgs e)
    {
        Button button = (Button)sender;
        //判别HiddenField是不是留存
        if (button.NamingContainer.FindControl(“HiddenField1”) != null)
        {
            //存在,把指标转换为HiddenField控件
            HiddenField hf = (HiddenField)button.NamingContainer.FindControl(“HiddenField1”);
            //取出HiddenField的Value值。
            string id = hf.Value;
           
            //抽取之后,就能够在此地管理你的政工了,上面只是简单抛出而已。
            objJs.JsAlert(“你选取的笔录主键ID是” + id);
        }
    }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;  //Insus.NET:要援引名称空间

1、RouteBase

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;

IF OBJECT_ID (‘[dbo].[Member]’) IS NOT NULL
DROP TABLE [dbo].[Member]

    public IDisposable GetWriteLock()
    {
      this._rwLock.EnterWriteLock();
      return (IDisposable)new System.Web.Routing.RouteCollection.WriteLockDisposable(this._rwLock);
    }

 

    public RouteBase Route { get; set; }

CREATE TABLE [dbo].[Member](
    [MemberId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NULL,
    [Email] [nvarchar](100) NULL,
 CONSTRAINT [PK__Member__0CF04B187F60ED59] PRIMARY KEY CLUSTERED 
(
    [MemberId]澳门新萄京, ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

    //来源于附加到 Route的
自定义变量会集
    public RouteValueDictionary DataTokens
    {
      get
      {
        return this._dataTokens;
      }
    }
    //那时候解析的路由对象
    public RouteBase Route { get; set; }

SET ANSI_NULLS ON
GO

    //为路由模板中的变量以正则表明式的形武设定一些羁绊标准,Key为变量名,Value为正则表达式

        //Insus.NET: 把挑选的值存到ViewState,你能够把它存任何能够保存的变量中,呵呵
        ViewState[“SelectedValue”]= Request.Form[“InsusRadio1”].ToString();    
        //Insus.NET: 下边连串,你能够从Insus.NET博客中下载
        InsusJsUtility objJs = new InsusJsUtility();

  • 注册路由映射,即注册路由模板和情理文件的相配关系,完成央浼U大切诺基L地址和管理须求的大意地址的分离,能够增长央求U宝马X5L可读性,SEO优化,灵活性,即诉求U哈弗L和管理央求的情理文件的变型互不影响
  • U库罗德L生成,依照登记的路由法则改造对应U奥迪Q7L,使用这种U奔驰M级L,刚好利用了路由登记的八面驶风,能够使原先生成的U奥迪Q3L不暂停,只须求修改路由安插的拍卖文件。

澳门新萄京 9澳门新萄京 10View Code

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
      RouteValueDictionary
values = this._parsedRoute.Match(httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2)

 

      public
WriteLockDisposable(ReaderWriterLockSlim rwLock)
      {
        this._rwLock =
rwLock;
      }

public partial class GridviewSingleSelection : System.Web.UI.Page
{
    //Insus.NET: new Member一个实例
    Member objMember = new Member();

    //假诺有定义,相配也要知足该约束
    public RouteValueDictionary Constraints { get; set; }
    //存款和储蓄额外的变量值
    public RouteValueDictionary DataTokens { get; set; }
    //路由变量暗中同意值,也不肯定要定义在路由模板中
    public RouteValueDictionary Defaults { get; set; }

成效如下,把挑选的值使用javascript Alert:

  private string
GetVirtualPathForRecipe(string
recipeName)

数据源,在可用的数据库内成立一个表[Member] 并插入三笔测量试验记录:

    {
      context.PostResolveRequestCache += new EventHandler(this.OnPostResolveRequestCache);
    }
    void
OnPostResolveRequestCache( object o,
EventArgs e)

澳门新萄京 11澳门新萄京 12View Code

    public static RouteCollection Routes
    {
      get
      {
        return
RouteTable._instance;
      }
    }
  }

澳门新萄京 13澳门新萄京 14View Code

  当然,可以传八个

                //Insus.NET: 下边那些是把表主键的值赋给变量value。借让你想取GridView的目录,可以利用e.Row.RowIndex.ToString()
                string value = DataBinder.Eval(e.Row.DataItem, “MemberId”).ToString(); //e.Row.RowIndex.ToString();

   澳门新萄京 15

        public Member()
        {
            //
            // TODO: Add constructor logic here
            //
        }

      void IDisposable.Dispose()
      {
        this._rwLock.ExitReadLock();
      }
    }

澳门新萄京 16澳门新萄京 17View Code

    protected override void
SetItem(int index, RouteBase item)
    {
      if (item == null)
        throw new ArgumentNullException(nameof(item));
      if (this.Contains(item))
        throw new ArgumentException(string.Format((IFormatProvider)CultureInfo.CurrentCulture,
System.Web.SR.GetString(“RouteCollection_DuplicateEntry”), new           object[0]),
nameof(item));
      this.RemoveRouteName(index);
      base.SetItem(index,
item);
    }

好了,时间难题不再作过多批注,如还有失水准,请联系Insus.NET,程序着重部分有详实的注释。

    //对变量私下认可值的印证
    var dataTokens = new RouteValueDictionary { { “defaultCity”, “BeiJing” }, { “defaultDays”, 2 } };

GO

6、IRouteConstraint

GridviewSingleSelection.aspx:

4、注册忽略路由(Ignore)

    private void Data_Binding()
    {
        this.GridView1.DataSource = objMember.GetMember();
        this.GridView1.DataBind();

    private bool ProcessConstraints(HttpContextBase httpContext, RouteValueDictionary values, RouteDirection routeDirection)
    {
      if (this.Constraints != null)
      {
        foreach (KeyValuePair<string, object> constraint in this.Constraints)
        {
          if (!this.ProcessConstraint(httpContext,
constraint.Value, constraint.Key, values, routeDirection))
          return false;
        }
      }
      return true;
    }

    }
    protected void ButtonSingleSelect_Click(object sender, EventArgs e)
    {
       //Insus.NET: 判定顾客是不是有取舍,若无选拔return
        if (Request.Form[“InsusRadio1”] == null) return;

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图