Como lidar com a elegância de URL de retorno ao usar Url Rewrite em ASP.NET 2.0 WebForms
-
11-09-2019 - |
Pergunta
Eu tenho uma pasta com várias páginas .aspx que eu quero restringir o acesso. Eu adicionei web.config para essa pasta com <deny users="?"/>
.
O problema é que ReturnUrl é auto-gerado com caminho físico para o arquivo .aspx enquanto eu estou usando UrlRewrite.
Existe uma maneira de manipular ReturnUrl sem fazer verificação de autenticação manual e redirecionamento? Existe uma maneira de ReturnUrl conjunto de code-behind ou de web.config?
EDIT 2 : Parece que 401 código de status nunca é capturado. Ele retorna 302 para página e redirecionamentos protegida à página de login com ReturnUrl. Ela não retorna 401 para página protegida. Hmm ... Interessante ... Ref: http://msdn.microsoft. com / en-us / library / aa480476.aspx
Isto torna as coisas mais difíceis ... Eu poderia ter de escrever regras de mapeamento reescrita reversa para ReturnUrl match regex e substituí-lo se ele não devolver 401 ... Se isso acontecer retorno 401 I tanto pode definir RawUrl para Response.RedirectLocation ou substituir ReturnUrl com RawUrl.
Alguém tem outras ideias?
Solução 3
acabei verificação de existência de ReturnUrl na URL e substitui-lo com RawUrl em EndRequest palco em Global.asax. Isso funciona para mim para agora ...
Este post me ajudou a configurá-lo.
protected void Application_EndRequest(object sender, EventArgs e)
{
string redirectUrl = this.Response.RedirectLocation;
if (!this.Request.RawUrl.Contains("ReturnUrl=") && !string.IsNullOrEmpty(redirectUrl))
{
this.Response.RedirectLocation = Regex.Replace(redirectUrl, "ReturnUrl=(?'url'[^&]*)", delegate(Match m)
{
return string.Format("ReturnUrl={0}", HttpUtility.UrlEncode(this.Request.RawUrl));
}, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
}
}
Outras dicas
Confira. Espero que isso ajude.
#region [ Imports ]
using System;
using System.Web;
using System.Web.Security;
#endregion
namespace Foo.Handlers
{
public class AuthModule : IHttpModule
{
#region IHttpModule Members
public void Init(HttpApplication application)
{
application.PostReleaseRequestState += delegate(object s, EventArgs e)
{
if (application.Response.StatusCode == 401)
application.Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(application.Request.RawUrl), true);
};
}
public void Dispose() { }
#endregion
}
}
<modules>
<add name="AuthModule" type="Foo.Handlers.AuthModule, Foo"/>
</modules>
Crie a seguinte adaptador de controle para reescrever a tag formulário com o para o atributo ação. I utilizado este app um ASP.NET 2.0 em conjunto com o Intelligencia url banner. I got it from este post do Gu .
Coloque esta classe na pasta App_Code:
using System.IO;
using System.Web;
using System.Web.UI;
public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter
{
protected override void Render(HtmlTextWriter writer)
{
base.Render(new RewriteFormHtmlTextWriter(writer));
}
}
public class RewriteFormHtmlTextWriter : HtmlTextWriter
{
public RewriteFormHtmlTextWriter(TextWriter writer) : base(writer)
{
base.InnerWriter = writer;
}
public RewriteFormHtmlTextWriter(HtmlTextWriter writer) : base(writer)
{
this.InnerWriter = writer.InnerWriter;
}
public override void WriteAttribute(string name, string value, bool fEncode)
{
// If the attribute we are writing is the "action" attribute, and we are not on a sub-control,
// then replace the value to write with the raw URL of the request - which ensures that we'll
// preserve the PathInfo value on postback scenarios
if ((name == "action"))
{
if (HttpContext.Current.Items["ActionAlreadyWritten"] == null)
{
// Because we are using the UrlRewriting.net HttpModule, we will use the
// Request.RawUrl property within ASP.NET to retrieve the origional URL
// before it was re-written. You'll want to change the line of code below
// if you use a different URL rewriting implementation.
value = HttpContext.Current.Request.RawUrl;
// Indicate that we've already rewritten the <form>'s action attribute to prevent
// us from rewriting a sub-control under the <form> control
HttpContext.Current.Items["ActionAlreadyWritten"] = true;
}
}
base.WriteAttribute(name, value, fEncode);
}
}
Em seguida, crie esse arquivo .browser em seus App_Browsers pasta:
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.HtmlControls.HtmlForm" adapterType="FormRewriterControlAdapter" />
</controlAdapters>
</browser>
</browsers>
Se você estiver usando ASP.NET 3.5, use ASP.NET UrlRouting vez. Mas você deve verificar a autorização manualmente.
http: //chriscavanagh.wordpress. COM / 2008/03/11 / aspnet-roteamento-goodbye-url reescrever /