简体   繁体   中英

Update HttpContext.Current.Request.QueryString

I have a function that is attempting to filter data based on what is in the HttpContext.Current.Request.QueryString . A recent "improvement" has changed how I have to filter what's being shown. Now I need to update the QueryString before my filtering functions run. Based on some other StackOverflow questions I have tried a few different ways but they haven't work.

    var queryString = HttpContext.Current.Request.QueryString;
    var nameValues = HttpUtility.ParseQueryString( queryString.ToString() );
    nameValues.Add( "IsDeleted", "False" );
    string url = HttpContext.Current.Request.Url.AbsolutePath;
    string updatedQuerySring = "?" + nameValues.ToString();
    HttpContext.Current.Response.Redirect( url + updatedQuerySring );

The above threw a system.Web.HttpException error "Server cannot set status after HTTP headers have been sent."

HttpContext.Current.Request.QueryString.Add( "IsDeleted", "False" );

and

    NameValueCollection newQuery = new NameValueCollection();
    foreach( var key in queryString.Keys ){
        var value = queryString[ key.ToString()];
        newQuery.Add( key.ToString(), value );
    }
    newQuery.Add( "IsDeleted", "False" );
    HttpContext.Current.Request.QueryString = newQuery;

both come up with "Error 20 Property or indexer 'System.Web.HttpRequest.QueryString' cannot be assigned to -- it is read only". How do you update the QueryString so that I can add the IsDeleted filter it?

EDIT it was suggested to keep it in a session or tempdata variable but that won't work as it is needed in more than 1 redirect.

You need to make httpcontenxt.current readonly property to false and assign parameters now.

PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
isreadonly.SetValue(HttpContext.Current.Request.QueryString, false, null);                
HttpContext.Current.Request.QueryString.Set(key, value);                
isreadonly.SetValue(HttpContext.Current.Request.QueryString, true, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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