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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1188096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:21:47  来源:igfitidea点击:

Truncating Query String & Returning Clean URL C# ASP.net

c#asp.neturlquery-stringtruncate

提问by Chris

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.

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

ie.

IE。

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

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

out: www.website.com/default.aspx

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

What would be the best way to achieve this?

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

采纳答案by Rob Levine

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

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));

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

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

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

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

GetLeftPart basicallys says "get the left part of the uri up tothe 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).

GetLeftPart 基本上是说“将 uri 的左侧部分放到我指定的部分”。这可以是 Scheme(只是 http:// 位)、Authority(www.website.com 部分)、Path(/default.aspx)或 Query(查询字符串)。

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

假设您在一个 aspx 网页上,那么您可以使用 Response.Redirect(newUrl) 来重定向调用者。

Hope that helps

希望有帮助

回答by DanDan

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.

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

回答by dariom

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.

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

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.

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

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_ReWriteor IIS 7.0 URL Rewrite Moduleis a great approach.
  • A custom IHttpModuleis a nice, reusable roll-your-own approach.
  • You can also do this in the global.asaxas you suggest
  • 如果您可以直接控制服务器环境,那么像ISAPI_ReWriteIIS 7.0 URL 重写模块这样的可配置服务器模块是一个很好的方法。
  • 自定义IHttpModule是一种不错的、可重用的、自己动手的方法。
  • 您也可以global.asax按照您的建议执行此操作

You should only use the 301response 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 301response code) will skip loading a URL like .../default.aspx?utm_source=twitter&utm_medium=social-mediaand load .../default.aspx- you'll never even know about the query string parameters.

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

Finally, you can use POSTmethod 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.

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

回答by Chris

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.

后跟一个函数来正确获取应用程序 URL。

Works perfectly.

完美运行。

回答by Michael Church

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

完成您需要对查询字符串执行的任何处理后,只需在问号上拆分 url:

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.

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

回答by Farooq Kaiser

Here is a simple trick

这是一个简单的技巧

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

dim reqURL = uri.GetLeftPart(UriPartial.Path)

回答by calmcajun

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,"");