HttpContext.RewritePath Método
Definição
Redireciona uma solicitação para um recurso para um caminho diferente daquele indicado pela URL solicitada.Redirects a request for a resource to a different path than the one that is indicated by the requested URL. RewritePath é usado no estado de sessão sem cookies para retirar as IDs de sessão das URLs.RewritePath is used in cookieless session state to strip session IDs from URLs.
Sobrecargas
| RewritePath(String, String, String, Boolean) |
Regrava a URL usando o caminho virtual fornecido, informações de caminho, informações de cadeia de caracteres de consulta e um valor booliano que especifica se o caminho do arquivo de cliente é definido como o caminho de regravação.Rewrites the URL using the given virtual path, path information, query string information, and a Boolean value that specifies whether the client file path is set to the rewrite path. |
| RewritePath(String, String, String) |
Regrava a URL usando o caminho, as informações de caminho e as informações de cadeia de caracteres de consulta especificados.Rewrites the URL by using the given path, path information, and query string information. |
| RewritePath(String, Boolean) |
Regrava a URL usando o caminho especificado e um valor booliano que especifica se o caminho virtual para recursos de servidor é modificado.Rewrites the URL using the given path and a Boolean value that specifies whether the virtual path for server resources is modified. |
| RewritePath(String) |
Regrava a URL usando o caminho fornecido.Rewrites the URL using the given path. |
RewritePath(String, String, String, Boolean)
Regrava a URL usando o caminho virtual fornecido, informações de caminho, informações de cadeia de caracteres de consulta e um valor booliano que especifica se o caminho do arquivo de cliente é definido como o caminho de regravação.Rewrites the URL using the given virtual path, path information, query string information, and a Boolean value that specifies whether the client file path is set to the rewrite path.
public:
void RewritePath(System::String ^ filePath, System::String ^ pathInfo, System::String ^ queryString, bool setClientFilePath);
public void RewritePath (string filePath, string pathInfo, string queryString, bool setClientFilePath);
member this.RewritePath : string * string * string * bool -> unit
Public Sub RewritePath (filePath As String, pathInfo As String, queryString As String, setClientFilePath As Boolean)
Parâmetros
- filePath
- String
O caminho virtual para o recurso que atende à solicitação.The virtual path to the resource that services the request.
- pathInfo
- String
Informações adicionais sobre o caminho a ser usado para o redirecionamento de URL.Additional path information to use for the URL redirect. Para obter mais informações, consulte PathInfo.For more information, see PathInfo.
- queryString
- String
A cadeia de caracteres de consulta de solicitação a ser usada para o redirecionamento de URL.The request query string to use for the URL redirect.
- setClientFilePath
- Boolean
true para definir o caminho do arquivo usado para os recursos de cliente para o valor do parâmetro filePath; caso contrário, false.true to set the file path used for client resources to the value of the filePath parameter; otherwise false.
Exceções
O parâmetro path não está no diretório raiz do aplicativo atual.The path parameter is not in the current application's root directory.
O parâmetro filePath não está no diretório raiz do aplicativo atual.The filePath parameter is not in the current application's root directory.
Exemplos
Para obter um exemplo de código, consulte a RewritePath(String) sobrecarga do método.For a code example, see the RewritePath(String) method overload.
Comentários
O filePath parâmetro não inclui o conteúdo do pathInfo parâmetro.The filePath parameter does not include the content of the pathInfo parameter. Para a URL http://www.microsoft.com/virdir/page.html/tail , o filePath parâmetro é http://www.microsoft.com/virdir/page.html , e o pathInfo parâmetro é tail.For the URL http://www.microsoft.com/virdir/page.html/tail, the filePath parameter is http://www.microsoft.com/virdir/page.html, and the pathInfo parameter is tail.
Para garantir que o caminho virtual usado para construir caminhos para recursos não seja modificado, defina o setClientFilePath parâmetro como false .To ensure that the virtual path that is used to construct paths to resources is not modified, set the setClientFilePath parameter to false. Um cenário comum no qual você pode querer definir setClientFilePath false é quando você precisa reescrever a URL, e você está usando temas e redirecionando a URL para um recurso localizado em uma pasta diferente do recurso solicitado.A common scenario in which you might want to set setClientFilePath to false is when you need to rewrite the URL, and you are using themes and redirecting the URL to a resource located in a different folder than the requested resource.
A regravação de URL é útil quando você deseja reestruturar as páginas em seu aplicativo Web e você deseja certificar-se de que as pessoas com as URLs antigas com indicadores ainda podem usá-las depois que você tiver movido as páginas.URL rewriting is useful when you want to restructure the pages in your Web application, and you want to make sure that people who have bookmarked old URLs can still use them after you have moved pages. A regravação de URL permite que você encaminhe solicitações de forma transparente para o local da nova página.URL rewriting enables you to transparently forward requests to the new page location.
Se você quiser habilitar um site para usar URLs mais amigáveis e otimizadas para mecanismos de pesquisa, uma alternativa mais robusta é usar o roteamento ASP.NET.If you want to enable a site to use URLs that are more user-friendly and are optimized for search engines, a more robust alternative is to use ASP.NET routing. Para obter mais informações, consulte ASP.net Routing.For more information, see ASP.NET Routing.
Aplica-se a
RewritePath(String, String, String)
Regrava a URL usando o caminho, as informações de caminho e as informações de cadeia de caracteres de consulta especificados.Rewrites the URL by using the given path, path information, and query string information.
public:
void RewritePath(System::String ^ filePath, System::String ^ pathInfo, System::String ^ queryString);
public void RewritePath (string filePath, string pathInfo, string queryString);
member this.RewritePath : string * string * string -> unit
Public Sub RewritePath (filePath As String, pathInfo As String, queryString As String)
Parâmetros
- filePath
- String
O caminho de regravação interno.The internal rewrite path.
- pathInfo
- String
Informações adicionais de caminho para um recurso.Additional path information for a resource. Para obter mais informações, consulte PathInfo.For more information, see PathInfo.
- queryString
- String
A cadeia de caracteres de consulta da solicitação.The request query string.
Exceções
O parâmetro path não está no diretório raiz do aplicativo atual.The path parameter is not in the current application's root directory.
O parâmetro filePath não está no diretório raiz do aplicativo atual.The filePath parameter is not in the current application's root directory.
Exemplos
Para um exemplo de código, incluindo um exemplo dessa sobrecarga de método, consulte a RewritePath(String) sobrecarga do método.For a code example, including an example of this method overload, see the RewritePath(String) method overload.
Comentários
O RewritePath método redireciona uma solicitação de um recurso para outro recurso sem alterar a URL.The RewritePath method redirects a request for a resource to another resource without changing the URL.
O filePath parâmetro não inclui o pathInfo conteúdo do parâmetro.The filePath parameter does not include the pathInfo parameter content. Para a URL http://www.microsoft.com/virdir/page.html/tail , o filePath parâmetro é http://www.microsoft.com/virdir/page.html , e o pathInfo parâmetro é tail.For the URL http://www.microsoft.com/virdir/page.html/tail, the filePath parameter is http://www.microsoft.com/virdir/page.html, and the pathInfo parameter is tail.
A regravação de URL é útil quando você deseja reestruturar as páginas em seu aplicativo Web e você deseja certificar-se de que as pessoas com as URLs antigas com indicadores ainda podem usá-las depois que você tiver movido as páginas.URL rewriting is useful when you want to restructure the pages in your Web application, and you want to make sure that people who have bookmarked old URLs can still use them after you have moved pages. A regravação de URL permite que você encaminhe solicitações de forma transparente para o local da nova página.URL rewriting enables you to transparently forward requests to the new page location.
Se você quiser habilitar um site para usar URLs mais amigáveis e otimizadas para mecanismos de pesquisa, uma alternativa mais robusta é usar o roteamento ASP.NET.If you want to enable a site to use URLs that are more user-friendly and are optimized for search engines, a more robust alternative is to use ASP.NET routing. Para obter mais informações, consulte ASP.net Routing.For more information, see ASP.NET Routing.
Aplica-se a
RewritePath(String, Boolean)
Regrava a URL usando o caminho especificado e um valor booliano que especifica se o caminho virtual para recursos de servidor é modificado.Rewrites the URL using the given path and a Boolean value that specifies whether the virtual path for server resources is modified.
public:
void RewritePath(System::String ^ path, bool rebaseClientPath);
public void RewritePath (string path, bool rebaseClientPath);
member this.RewritePath : string * bool -> unit
Public Sub RewritePath (path As String, rebaseClientPath As Boolean)
Parâmetros
- path
- String
O caminho de regravação interno.The internal rewrite path.
- rebaseClientPath
- Boolean
true para redefinir o caminho virtual; false para manter o caminho virtual inalterado.true to reset the virtual path; false to keep the virtual path unchanged.
Exceções
O parâmetro path é null.The path parameter is null.
O parâmetro path não está no diretório raiz do aplicativo atual.The path parameter is not in the current application's root directory.
Exemplos
Para obter um exemplo de código, consulte a RewritePath(String) sobrecarga do método.For a code example, see the RewritePath(String) method overload.
Comentários
O HttpContext.RewritePath(String, Boolean) método é chamado pelo HttpContext.RewritePath(String) método com o rebaseClientPath parâmetro definido como true .The HttpContext.RewritePath(String, Boolean) method is called by the HttpContext.RewritePath(String) method with the rebaseClientPath parameter set to true. Para garantir que o caminho virtual usado para construir caminhos para recursos não seja modificado, defina o rebaseClientPath parâmetro como false .To ensure that the virtual path that is used to construct paths to resources is not modified, set the rebaseClientPath parameter to false. Um cenário comum no qual você pode querer definir rebaseClientPath false é quando você precisa reescrever a URL, e você está usando temas e redirecionando a URL para um recurso localizado em uma pasta diferente do recurso solicitado.A common scenario in which you might want to set rebaseClientPath to false is when you need to rewrite the URL, and you are using themes and redirecting the URL to a resource located in a different folder than the requested resource.
A regravação de URL é útil quando você deseja reestruturar as páginas em seu aplicativo Web e você deseja certificar-se de que as pessoas com as URLs antigas com indicadores ainda podem usá-las depois que você tiver movido as páginas.URL rewriting is useful when you want to restructure the pages in your Web application, and you want to make sure that people who have bookmarked old URLs can still use them after you have moved pages. A regravação de URL permite que você encaminhe solicitações de forma transparente para o local da nova página.URL rewriting enables you to transparently forward requests to the new page location.
Se você quiser habilitar um site para usar URLs mais amigáveis e otimizadas para mecanismos de pesquisa, uma alternativa mais robusta é usar o roteamento ASP.NET.If you want to enable a site to use URLs that are more user-friendly and are optimized for search engines, a more robust alternative is to use ASP.NET routing. Para obter mais informações, consulte ASP.net Routing.For more information, see ASP.NET Routing.
Aplica-se a
RewritePath(String)
Regrava a URL usando o caminho fornecido.Rewrites the URL using the given path.
public:
void RewritePath(System::String ^ path);
public void RewritePath (string path);
member this.RewritePath : string -> unit
Public Sub RewritePath (path As String)
Parâmetros
- path
- String
O caminho de regravação interno.The internal rewrite path.
Exceções
O parâmetro path é null.The path parameter is null.
O parâmetro path não está no diretório raiz do aplicativo atual.The path parameter is not in the current application's root directory.
Exemplos
O exemplo a seguir mostra como usar o RewritePath método para habilitar um site da Web para responder a URLs que não refletem a estrutura de arquivos no site.The following example shows how to use the RewritePath method to enable a Web site to respond to URLs that do not reflect the file structure in the Web site. O primeiro bloco de código é uma página da Web ASP.NET chamada RewritePath. aspx.The first block of code is an ASP.NET Web page that is named RewritePath.aspx. Ele requer uma cadeia de caracteres de consulta.It requires a query string. Se o nome do seu site for WebSite1, a URL http://localhost/WebSite1/RewritePath.aspx?page=1 exibirá "página 1" no navegador.If the name of your site is WebSite1, the URL http://localhost/WebSite1/RewritePath.aspx?page=1 displays "Page 1" in the browser. O bloco de código que segue a página da Web é o Application_BeginRequest manipulador de eventos no arquivo global. asax.The block of code that follows the Web page is the Application_BeginRequest event handler in the Global.asax file. Esse código intercepta as solicitações de URLs, como http://localhost/WebSite1/page1 e as converte para o formulário necessário para RewritePath. aspx antes de serem processadas.This code intercepts requests for URLs such as http://localhost/WebSite1/page1 and converts them to the form that is required for RewritePath.aspx before they are processed. Portanto, a URL http://localhost/WebSite1/page1 invoca RewritePath. aspx com o parâmetro Query-String que exibe "Page 1" no navegador.Therefore, the URL http://localhost/WebSite1/page1 invokes RewritePath.aspx with the query-string parameter that displays "Page 1" in the browser. Se uma URL como http://localhost/WebSite1/page1 é recebida, uma sobrecarga de RewritePath é invocada que permite que você forneça um valor para a PathInfo propriedade, bem como um parâmetro de cadeia de caracteres de consulta.If a URL such as http://localhost/WebSite1/page1 is received, an overload of RewritePath is invoked that enables you to provide a value for the PathInfo property as well as a query string parameter.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Page=" + Request.QueryString["page"] + " PathInfo=" + Request.PathInfo;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Label1.Text = "Page=" & Request.QueryString("page") & " PathInfo=" & Request.PathInfo
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
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");
}
}
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim originalPath As String = HttpContext.Current.Request.Path.ToLower()
If originalPath.Contains("/page1") Then
Context.RewritePath(originalPath.Replace("/page1", "/RewritePath.aspx?page=page1"))
End If
If originalPath.Contains("/page2") Then
Context.RewritePath(originalPath.Replace("/page2", "/RewritePath.aspx"), "pathinfo", "page=page2")
End If
End Sub
Comentários
O RewritePath(String) método redireciona uma solicitação de um recurso para um caminho diferente daquele indicado pela URL solicitada.The RewritePath(String) method redirects a request for a resource to a different path than the one that is indicated by the requested URL. Se você precisar redefinir o caminho virtual para que as solicitações do cliente para os recursos do servidor sejam resolvidas corretamente, use a sobrecarga desse método que usa o rebaseClientPath parâmetro e defina o parâmetro como false .If you have to reset the virtual path so that requests from the client for server resources resolve correctly, use the overload of this method that takes the rebaseClientPath parameter and set the parameter to false.
A regravação de URL é útil quando você deseja reestruturar as páginas em seu aplicativo Web e você deseja certificar-se de que as pessoas com as URLs antigas com indicadores ainda podem usá-las depois que você tiver movido as páginas.URL rewriting is useful when you want to restructure the pages in your Web application, and you want to make sure that people who have bookmarked old URLs can still use them after you have moved pages. A regravação de URL permite que você encaminhe solicitações de forma transparente para o local da nova página.URL rewriting enables you to transparently forward requests to the new page location.
Se você quiser habilitar um site para usar URLs mais amigáveis e otimizadas para mecanismos de pesquisa, uma alternativa mais robusta é usar o roteamento ASP.NET.If you want to enable a site to use URLs that are more user-friendly and are optimized for search engines, a more robust alternative is to use ASP.NET routing. Para obter mais informações, consulte ASP.net Routing.For more information, see ASP.NET Routing.