我的ReturnUrl正在重复

时间:2013-07-09 20:25:33

标签: c# asp.net url redirect

我有一个页面,如果您没有我想要的cookie,它会将您重定向到创建cookie的页面。基本上如果你没有告诉我你已经够老了,你必须重定向到一个页面并给我你的年龄。长话短说如果我被重定向到这个页面,我要求你年龄,最终用户不会决定给我年龄,并点击同一页面或另一页面。我的代码添加到现有字符串上。

protected void Page_Load(object sender, EventArgs e)
    {       
        string referrer = Request.UrlReferrer.ToString();

            if (Request.Cookies["Age"] == null)
                Response.Redirect("/AgeRestricted/?ReturnUrl=" + referrer);


    }

如果我调用此页面加载多次,我的URL会变得非常难看。

http://localhost:14028/AgeRestricted/?ReturnUrl=http://localhost:14028/AgeRestricted/?ReturnUrl=http://localhost:14028/

它就像它连接到现有的。我有办法防止这种情况吗?

我基本上想拥有它,以便我在ReturnUrl QueryString中只有1个参数,因此如果已经有值,它将不会重复。

2 个答案:

答案 0 :(得分:1)

您可以使用Uri类来获取没有查询字符串的referrer部分。例如:

if (Request.Cookies["Age"] == null)
{
    string referrer = Request.UrlReferrer.GetLeftPart(UriPartial.Path);
    Response.Redirect(referrer);
}

有关GetLeftPath的详细信息,请参阅:http://msdn.microsoft.com/en-us/library/system.uri.getleftpart.aspx

答案 1 :(得分:0)

以下是解决问题的代码。不知道为什么我的最后一个答案被删除了。

 string url = HttpContext.Current.Request.Url.AbsoluteUri;

            if (Request.Cookies["Age"] == null)
                Response.Redirect("/AgeRestricted/?ReturnUrl=" + url);