查询字符串作为url的一部分

问题描述:

我有一个查询字符串http://www.sample.com?q=asdasdsdasd的网址。是否有可能修改查询字符串,以便我可以用/ myaccount替换它,即最终url将看起来像http://www.sample.com/myaccount查询字符串作为url的一部分

+2

您将如何在参数传递? – Oded 2012-02-01 09:49:47

+0

@Oded/myaccount也应该有参数 – 2012-02-01 09:55:17

结账url rewriting。你可能无法直接获得/ myaccount,但你可以整理你的网址,使它们对SEO更具可读性和有意义。

你将能够使用,让您的网址类似于以下内容:

www.sample.com/account/asdaasdasd 

如果丢失的查询字符串一起,你将不能够在所有访问它。除非你实现了某种形式的临时代码来获取查询字符串,否则将其存储在一个会话中,然后重定向到你的url并将其返回到那里。

string destUrl = string.Format("{0}://{1}{2}/",Request.Url.Scheme,Request.Url.Authority,Request.Url.AbsolutePath); 
if (destUrl.EndsWith("/")) 
    destUrl = destUrl.TrimEnd(new char[] { '/' }); 
if (!string.IsNullOrEmpty(Request.QueryString["paramName"])) { 
    destUrl = string.Format("{0}?paramName={1}", destUrl, "paramValueHere"); 
Response.Redirect(destUrl); 

我认为你指的是URL重写。

这是一个相当常用的博客中关于URL重写:

http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

或者,如果你有IIS7,它现在​​变得更加容易:

http://www.iis.net/download/urlrewrite


在条款?q=asdasdsdasd/myaccount虽然,我不明白。第一个URL看起来像是一个典型的搜索查询,第二个URL是一个可能使用cookie等来获取变量的URL(就像用户帐户一样)。

但URL重写,可以使用,这样,如果你有一个像URL,用户配置文件:

www.sample.com?userprofile.aspx?user=johnsmith

这可以被改写使用johnsmith部分像一个变量:

www.sample.com/user/johnsmith

随着简单字符串manipulat被离子你会做得一样:

string urlWithQuerystring = "http://www.sample.com?q=asdasdsdasd"; 
int queryStringPos = urlWithQuerystring.IndexOf("?"); 
string newUrl = String.Format("{0}/myaccount/", urlWithQuerystring.Substring(0, queryStringPos)); 

使用此代码在您的Global.asax:

void Application_BeginRequest(object sender, EventArgs e) 
{ 

    string[] parts = Request.RawUrl.Split(new char[]{'/'}); 

    if(Part[1] == "myaccount")) 
     Context.RewritePath("http://www.sample.com?q=" + Part[2]); 

} 

,然后使用这个地址 http://www.sample.com/myaccount/asdasdasd