Programing

C #을 사용하여 asp.net의 쿼리 문자열에서 항목을 제거하려면 어떻게해야합니까?

lottogame 2021. 1. 9. 09:16
반응형

C #을 사용하여 asp.net의 쿼리 문자열에서 항목을 제거하려면 어떻게해야합니까?


내 URL에서 "언어"쿼리 문자열을 제거하고 싶습니다. 어떻게 할 수 있습니까? (Asp.net 3.5, c # 사용)

Default.aspx?Agent=10&Language=2

"Language = 2"를 제거하고 싶지만 언어가 첫 번째, 중간 또는 마지막입니다. 그래서 나는 이것을 가질 것이다

Default.aspx?Agent=20

얼마 전에 비슷한 질문 에 대답했습니다 . 기본적으로, 가장 좋은 방법은 클래스 사용하는 것입니다 HttpValueCollection, QueryString속성은 사실이다, 불행히도는 .NET 프레임 워크의 내부입니다. Reflector를 사용하여 가져 와서 Utils 클래스에 배치 할 수 있습니다. 이렇게하면 NameValueCollection과 같은 쿼리 문자열을 조작 할 수 있지만 모든 URL 인코딩 / 디코딩 문제가 처리됩니다.

HttpValueCollectionextends NameValueCollection는 인코딩 된 쿼리 문자열 (앰퍼샌드 및 물음표 포함)을 사용하는 생성자를 가지며 ToString()나중에 기본 컬렉션에서 쿼리 문자열을 다시 작성 하는 메서드를 재정의합니다 .


HttpRequest.QueryString 인 경우 컬렉션을 쓰기 가능한 컬렉션으로 복사하고 원하는대로 사용할 수 있습니다.

NameValueCollection filtered = new NameValueCollection(request.QueryString);
filtered.Remove("Language");

여기에 간단한 방법이 있습니다. 반사경이 필요하지 않습니다.

    public static string GetQueryStringWithOutParameter(string parameter)
    {
        var nameValueCollection = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.QueryString.ToString());
        nameValueCollection.Remove(parameter);
        string url = HttpContext.Current.Request.Path + "?" + nameValueCollection;

        return url;
    }

컬렉션은 읽기 전용 QueryString.ToString()이므로 여기 가 필요 Request.QueryString합니다.


드디어,

hmemcpy 대답은 전적으로 저에게 있었고 대답 한 다른 친구들에게 감사드립니다.

Reflector를 사용하여 HttpValueCollection을 잡고 다음 코드를 작성했습니다.

        var hebe = new HttpValueCollection();
        hebe.Add(HttpUtility.ParseQueryString(Request.Url.Query));

        if (!string.IsNullOrEmpty(hebe["Language"]))
            hebe.Remove("Language");

        Response.Redirect(Request.Url.AbsolutePath + "?" + hebe );

여기에서 개인적으로 선호하는 것은 쿼리를 다시 작성하거나 더 낮은 지점에서 namevaluecollection으로 작업하는 것이지만, 비즈니스 로직이 그다지 유용하지 않고 때로는 반영이 실제로 필요한 경우가 있습니다. 이러한 상황에서는 다음과 같이 잠시 동안 읽기 전용 플래그를 끌 수 있습니다.

// reflect to readonly property
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);

// remove
this.Request.QueryString.Remove("foo");

// modify
this.Request.QueryString.Set("bar", "123");

// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);

이 시도 ...

PropertyInfo isreadonly   =typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);    

isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Remove("foo");

Request 개체에서 Querystring을 수정 하려는지 여부를 명확하게 밝히지 않습니다. 이 속성은 읽기 전용이므로 문자열을 엉망으로 만들고 싶다고 가정합니다.

... 어떤 경우에는 경계선이 사소합니다.

  • 요청에서 쿼리 문자열을 가져옵니다.
  • .split () '&'에
  • "언어"로 시작하는 모든 것을 찾아 내고 버리면서 새 문자열로 다시 결합합니다.

Get the querystring collection, parse it into a (name=value pair) string, excluding the one you want to REMOVE, and name it newQueryString

Then call Response.Redirect(known_path?newqueryString);


  1. Gather your query string by using HttpContext.Request.QueryString. It defaults as a NameValueCollection type.
  2. Cast it as a string and use System.Web.HttpUtility.ParseQueryString() to parse the query string (which returns a NameValueCollection again).
  3. You can then use the Remove() function to remove the specific parameter (using the key to reference that parameter to remove).
  4. Use case the query parameters back to a string and use string.Join() to format the query string as something readable by your URL as valid query parameters.

See below for a working example, where param_to_remove is the parameter you want to remove.

Let's say your query parameters are param1=1&param_to_remove=stuff&param2=2. Run the following lines:

var queryParams = System.Web.HttpUtility.ParseQueryString(HttpContext.Request.QueryString.ToString());
queryParams.Remove("param_to_remove");
string queryString = string.Join("&", queryParams.Cast<string>().Select(e => e + "=" + queryParams[e]));

Now your query string should be param1=1&param2=2.


You're probably going to want use a Regular Expression to find the parameter you want to remove from the querystring, then remove it and redirect the browser to the same file with your new querystring.


Yes, there are no classes built into .NET to edit query strings. You'll have to either use Regex or some other method of altering the string itself.


If you have already the Query String as a string, you can also use simple string manipulation:

int pos = queryString.ToLower().IndexOf("parameter=");
if (pos >= 0)
{
    int pos_end = queryString.IndexOf("&", pos);
    if (pos_end >= 0)   // there are additional parameters after this one
        queryString = queryString.Substring(0, pos) + queryString.Substring(pos_end + 1);
    else
        if (pos == 0) // this one is the only parameter
            queryString = "";
        else        // this one is the last parameter
            queryString=queryString.Substring(0, pos - 1);
}

well I have a simple solution , but there is a little javascript involve.

assuming the Query String is "ok=1"

    string url = Request.Url.AbsoluteUri.Replace("&ok=1", "");
   url = Request.Url.AbsoluteUri.Replace("?ok=1", "");
  Response.Write("<script>window.location = '"+url+"';</script>");

string queryString = "Default.aspx?Agent=10&Language=2"; //Request.QueryString.ToString();
string parameterToRemove="Language";   //parameter which we want to remove
string regex=string.Format("(&{0}=[^&\s]+|{0}=[^&\s]+&?)",parameterToRemove);
string finalQS = Regex.Replace(queryString, regex, "");

https://regexr.com/3i9vj


Parse Querystring into a NameValueCollection. Remove an item. And use the toString to convert it back to a querystring.

using System.Collections.Specialized;

NameValueCollection filteredQueryString = System.Web.HttpUtility.ParseQueryString(Request.QueryString.ToString());
filteredQueryString.Remove("appKey");

var queryString = '?'+ filteredQueryString.ToString();

ReferenceURL : https://stackoverflow.com/questions/529551/how-can-i-remove-item-from-querystring-in-asp-net-using-c

반응형