简体   繁体   English

如何从网址中删除查询字符串参数?

[英]How to remove query string parameters from the url?

Assume I have the link http://www.somesite.com/file.aspx?a=1&b=2 假设我有链接http://www.somesite.com/file.aspx?a=1&b=2

And now I want to remove all the parameters, so it becomes: 现在我想删除所有参数,所以它变成:

http://www.somesite.com/file.aspx http://www.somesite.com/file.aspx

Or I may want to remove only 1 of the parameters such as 或者我可能只想删除其中的一个参数,例如

http://www.somesite.com/file.aspx?b=2 http://www.somesite.com/file.aspx?b=2

Is there a way to do the above in C#? 有没有办法在C#中执行上述操作? What is happening is that I am coming from another page with a parameter called edit in the url, but when the page does a post back, the edit parameter is still there, so it still thinks it is in edit mode. 发生的事情是我来自另一个页面,在网址中有一个名为edit的参数,但当页面回发时,编辑参数仍然存在,所以它仍然认为它处于编辑模式。 Example: 例:

User A goes to page one.aspx and clicks on an edit link. 用户A转到第one.aspx页并点击编辑链接。 They are taken to two.aspx?edit=true. 他们被带到two.aspx?edit = true。 During page load, it sees the the query string parameter edit is not null and it puts the contents in edit mode. 在页面加载期间,它看到查询字符串参数edit不为null并且它将内容置于编辑模式。 Once the user is done editing, the page is refreshed, but the url is still two.aspx?edit=true and keeps the contents in edit mode, when in fact it should be two.aspx 用户完成编辑后,页面会刷新,但网址仍为two.aspx?edit = true并保持内容处于编辑模式,实际上应该是two.aspx

Request.Querystring is read-only collection - You cannot modify that. Request.Querystring是只读集合 - 您无法修改它。

If you need to remove or change the param in querystring only way out is to trigger a new GET request with updated querystring - This means you will have to do Response.Redirect with updated URL. 如果您需要删除或更改查询字符串中的参数,那么只能触发带有更新的查询字符串的新GET请求 - 这意味着您必须使用更新的URL执行Response.Redirect。 This will cause you lose the viewstate of the current page. 这将导致您丢失当前页面的视图状态。

使用PostBackUrl属性,例如:

<asp:Button ID="DoneEditingButton" runat="server" Text="Done editing" PostBackUrl="~/two.aspx" />

当您完成编辑后,您正在进行回发,所以只需定义要发布到two.aspx的操作,而不是仅仅回发到自己,这样就会删除get参数。

如何检查Page.IsPostBack以查看当前请求是否为回发?

if you have only string, you can use: 如果你只有字符串,你可以使用:

strinULR.Split('?').First();

or 要么

strinULR.Split('?').FirstOrDefault();

Late but you can do this to remove query string from URL without another GET Request. 迟到但您可以执行此操作以从URL中删除查询字符串而无需其他GET请求。 http://www.codeproject.com/Tips/177679/Removing-Deleting-Querystring-in-ASP-NET http://www.codeproject.com/Tips/177679/Removing-Deleting-Querystring-in-ASP-NET

Try something like this. 尝试这样的事情。

if (url.Contains("?"))
            url = url.Substring(0, url.IndexOf("?"));

In this example, I'm checking if the url even contains a query string, and if it does, subtracting getting the "left part" of the string prior to the ?. 在这个例子中,我正在检查url是否包含查询字符串,如果是,则减去在?之前获取字符串的“左侧部分”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM