截断查询字符串& 返回干净的 URL C# ASP.net

发布于 2024-07-27 22:12:31 字数 277 浏览 2 评论 0原文

我想获取原始 URL,截断查询字符串参数,然后返回 URL 的清理版本。 我希望它发生在整个应用程序中,因此通过 global.asax 执行将是理想的选择。 另外,我认为 301 重定向也是合适的。

IE。

输入:www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media

输出:www.website.com/default.aspx

实现此目标的最佳方法是什么?

I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole application, so performing through the global.asax would be ideal. Also, I think a 301 redirect would be in order as well.

ie.

in: www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media

out: www.website.com/default.aspx

What would be the best way to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

悟红尘 2024-08-03 22:12:33

我猜您想这样做是因为您希望您的用户看到漂亮的 URL。 让客户端“更改”地址栏中 URL 的唯一方法是将其发送到新位置 - 即您需要重定向它们。

查询字符串参数会影响页面的输出吗? 如果是这样,您将必须了解如何维护请求之间的状态(会话变量、cookie 等),因为一旦您重定向到没有它们的页面,您的查询字符串参数就会丢失。

有几种方法可以在全局范围

  • 内执行此操作(按优先顺序): 如果您可以直接控制服务器环境,则可以使用可配置的服务器模块,例如 ISAPI_ReWriteIIS 7.0 URL 重写模块是一个很好的方法。
  • 自定义 IHttpModule是一种很好的、​​可重复使用的、自己动手的方法。
  • 您也可以按照您的建议在 global.asax 中执行此操作。

如果资源确实已永久移动,则应仅使用 301 响应代码。 同样,这取决于您的应用程序是否需要使用查询字符串参数。 如果您使用永久重定向,浏览器(遵循 301 响应代码)将跳过加载类似 .../default.aspx?utm_source=twitter&utm_medium=social-media< /em> 并加载 .../default.aspx - 您甚至永远不会知道查询字符串参数。

最后,您可以使用 POST 方法请求。 这为您提供了干净的 URL 并允许您传递参数,但仅适用于您使用 JavaScript 创建的

元素或请求。

I'm guessing that you want to do this because you want your users to see pretty looking URLs. The only way to get the client to "change" the URL in its address bar is to send it to a new location - i.e. you need to redirect them.

Are the query string parameters going to affect the output of your page? If so, you'll have to look at how to maintain state between requests (session variables, cookies, etc.) because your query string parameters will be lost as soon as you redirect to a page without them.

There are a few ways you can do this globally (in order of preference):

  • If you have direct control over your server environment then a configurable server module like ISAPI_ReWrite or IIS 7.0 URL Rewrite Module is a great approach.
  • A custom IHttpModule is a nice, reusable roll-your-own approach.
  • You can also do this in the global.asax as you suggest

You should only use the 301 response code if the resource has indeed moved permanently. Again, this depends on whether your application needs to use the query string parameters. If you use a permanent redirect a browser (that respects the 301 response code) will skip loading a URL like .../default.aspx?utm_source=twitter&utm_medium=social-media and load .../default.aspx - you'll never even know about the query string parameters.

Finally, you can use POST method requests. This gives you clean URLs and lets you pass parameters in, but will only work with <form> elements or requests you create using JavaScript.

疯了 2024-08-03 22:12:33

这是一个简单的技巧

Dim uri = New Uri(Request.Url.AbsoluteUri)

dim reqURL = uri.GetLeftPart(UriPartial.Path)

Here is a simple trick

Dim uri = New Uri(Request.Url.AbsoluteUri)

dim reqURL = uri.GetLeftPart(UriPartial.Path)
软甜啾 2024-08-03 22:12:33

这是获取根路径的快速方法,无需完整路径和查询。

string path = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,"");

Here is a quick way of getting the root path sans the full path and query.

string path = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,"");
后知后觉 2024-08-03 22:12:33

这可能看起来好一点。

    string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);

    if (rawUrl.Contains("/post/"))
    {
        bool hasQueryStrings = Request.QueryString.Keys.Count > 1;

        if (hasQueryStrings)
        {
            Uri uri = new Uri(rawUrl);
            rawUrl = uri.GetLeftPart(UriPartial.Path);

            HtmlLink canonical = new HtmlLink();
            canonical.Href = rawUrl;
            canonical.Attributes["rel"] = "canonical";
            Page.Header.Controls.Add(canonical);
        }
    }

接下来是正确获取应用程序 URL 的函数。

工作完美。

This may look a little better.

    string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);

    if (rawUrl.Contains("/post/"))
    {
        bool hasQueryStrings = Request.QueryString.Keys.Count > 1;

        if (hasQueryStrings)
        {
            Uri uri = new Uri(rawUrl);
            rawUrl = uri.GetLeftPart(UriPartial.Path);

            HtmlLink canonical = new HtmlLink();
            canonical.Href = rawUrl;
            canonical.Attributes["rel"] = "canonical";
            Page.Header.Controls.Add(canonical);
        }
    }

Followed by a function to properly fetch the application URL.

Works perfectly.

旧伤慢歌 2024-08-03 22:12:33

看一下 UriBuilder 类。 您可以使用 url 字符串创建一个,然后该对象将解析该 url 并让您仅访问所需的元素。

Take a look at the UriBuilder class. You can create one with a url string, and the object will then parse this url and let you access just the elements you desire.

翻身的咸鱼 2024-08-03 22:12:33

完成对查询字符串所需的任何处理后,只需将问号上的 url 分开即可:

Dim _CleanUrl as String = Request.Url.AbsoluteUri.Split("?")(0)
Response.Redirect(_CleanUrl)

当然,我的解决方案是在 VB.NET 中,但我认为它可以很容易地移植。 由于我们只查找拆分的第一个元素,因此当没有查询字符串时,它甚至会优雅地“失败”。

After completing whatever processing you need to do on the query string, just split the url on the question mark:

Dim _CleanUrl as String = Request.Url.AbsoluteUri.Split("?")(0)
Response.Redirect(_CleanUrl)

Granted, my solution is in VB.NET, but I'd imagine that it could be ported over pretty easily. And since we are only looking for the first element of the split, it even "fails" gracefully when there is no querystring.

兲鉂ぱ嘚淚 2024-08-03 22:12:31

System.Uri 是你的朋友。 它有许多有用的实用程序,但您想要的是 GetLeftPart:

 string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
 Uri uri = new Uri(url);
 Console.WriteLine(uri.GetLeftPart(UriPartial.Path));

这给出了输出: http:// /www.website.com/default.aspx

[Uri 类确实需要指定协议 http://]

GetLeftPart 基本上是说“获取 uri 的左侧部分直到并包括 我指定的部分”。 这可以是方案(只是 http:// 位)、权限(www.website.com 部分) 、路径(/default.aspx)或查询(查询字符串)。

假设您正在访问 aspx 网页,则可以使用 Response.Redirect(newUrl) 来重定向调用者。

System.Uri is your friend here. This has many helpful utilities on it, but the one you want is GetLeftPart:

 string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
 Uri uri = new Uri(url);
 Console.WriteLine(uri.GetLeftPart(UriPartial.Path));

This gives the output: http://www.website.com/default.aspx

[The Uri class does require the protocol, http://, to be specified]

GetLeftPart basicallys says "get the left part of the uri up to and including the part I specify". This can be Scheme (just the http:// bit), Authority (the www.website.com part), Path (the /default.aspx) or Query (the querystring).

Assuming you are on an aspx web page, you can then use Response.Redirect(newUrl) to redirect the caller.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文