altering QueryString parameters / values

寵の児 提交于 2020-01-06 08:11:38

问题


I would like to better understand the issue of setting new parameters to a url and retrieve it via

var ParaValue = Request.QueryString["parameterName"];

so if I have a URL : "http://www.myWebsite.aspx?UserName=Alice"

I will retrieve it via example above

string uName = Request.QueryString["UserName"].ToString();

but what if I want to alter value e.g. make UserName = "Ralf"

  • Re Edit

when a button is pressed , there is a parameter "state" that holds a reference to wich button was pressed the value of state was = "none" now i want to set it to img_button1.

i am not even sending the actuall imgbutton id

i am hard coding it just for testing /referencing

so i could know i am in the stage of event reaquested by the procidure of the given event of button1

when event triggerd by img_button2

i whould then want to set the state to "img_button2" etc'


回答1:


after I have made my research (I couldn't mark any answer kindly given here on my post) then I tested two options I've encountered in this Stack Overflow Page:

first option (given by Ahmad Mageed) I have tested to work just fine . and readability was easy to understand (as I am still fresh to asp.net 'tricks')

then followed the answer by annakata which was remarkably improved approach in the way that you don't actually have to redirect to achieve result - Query String IS modified

after playing around i have desided to follow annakatas approach and make a helper method that was using also a redirerion option with modified QueryString Parameters & values.

public void QuerStrModify(string CurrQS_ParamName, string NewQs_paramName, string NewPar_Value, bool redirectWithNewQuerySettings = false)
{

    // 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(CurrQS_ParamName);

    // modify 
    this.Request.QueryString.Set(NewQs_paramName, NewPar_Value);

    // make collection readonly again 
    isReadOnly.SetValue(this.Request.QueryString, true, null);
    string FullUrl = Request.Url.AbsolutePath;
    if (redirectWithNewQuerySettings)
    {
        Response.Redirect(string.Join("?", FullUrl, this.Request.QueryString));
    }

}

i find it very helpful to someone that has Considerably less experience with asp.net developmet so i posted it as my version of correct answer , as i see it . i hope it'll help somoeone else that seeks the same Solution.

feel free to further improve it , as i mentiond I'm not a proven talent ..yet.




回答2:


You can use HttpModule

public class SimpleRewriter : System.Web.IHttpModule
{

    HttpApplication _application = null;

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new System.EventHandler(context_BeginRequest);
        _application = context;
    }

    public void Dispose()
    {
    }

    private void context_BeginRequest(object sender, System.EventArgs e)
    {
        string requesturl =
            _application.Context.Request.Path.Substring(0,
                _application.Context.Request.Path.LastIndexOf("//")
            );

        string[] parameters = requesturl.Split(new char[] { '/' });

        if (parameters.Length > 1)
        {
            string firstname = parameters[1];
            string lastname = parameters[2];


            //Here you can modify your parameters or your url

            _application.Context.RewritePath("~/unfriendly.aspx?firstname=" +
                firstname + "&lastname=" + lastname);

        }
    }
}

Link : http://msdn.microsoft.com/en-us/library/ms972974.aspx

Registering :

<configuration>
  <system.web>
    <httpModules>
      <add name="SimpleRewriter" type="SimpleRewriter"/>
     </httpModules>
  </system.web>
</configuration>

Link : http://msdn.microsoft.com/en-us/library/ms227673%28v=vs.100%29.aspx




回答3:


The problem here is a "source of truth" problem. The NameValueCollection exposed by HttpRequest.QueryString exposes the query string and should not be modified because the query string was supplied by the caller. If the application has a UserName query string argument but it may need to be changed, such as for testing, wrap it in a method that can get it form an alternate source if needed. For example:

// A very simple container
public static class SystemInfo
{
    // This would be an instance of QueryStringUserInfo
    // by default but could be changed for testing.
    public IUserInfo UserInfo
    {
        get;
        private set;
    }
}

// An interface that contains the user operations 
public interface IUserInfo
{
    string UserName { get; }
}

// Get the user name from the query string. This would
// be the default.
public class QueryStringUserInfo: IUserInfo
{
    public string UserName
    {
        get
        {
            return Request.QueryString["UserName"].ToString();
        }
    }
}

// Get the user name from the query string. This would
// be the default.
public class TestUserInfo: IUserInfo
{
    public string UserName
    {
        get
        {
            return "Foo";
        }
    }
}

So, rather than call the QueryString directly for the user name (or whichever piece of information), call the property on SystemInfo (horrible name but you get the point). It allows the source of the settings to be changed, such as if the code is used outside a web page or for testing.



来源:https://stackoverflow.com/questions/12544893/altering-querystring-parameters-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!