Converting/accessing QueryString values in ASP.NET

后端 未结 7 1605
长情又很酷
长情又很酷 2021-01-30 14:44

I\'m curious what everyone does for handling/abstracting the QueryString in ASP.NET. In some of our web apps I see a lot of this all over the site:

int val = 0;         


        
7条回答
  •  心在旅途
    2021-01-30 15:31

    I tend to like the idea of abstracting them as properties. For example:

            public int age { 
            get
            {
                if (Request.QueryString["Age"] == null)
                    return 0;
                else
                    return int.Parse(Request.QueryString["Age"]);                                    
            }
        }
    

    You could add more validation if you wanted to. But I tend to like wrapping all of my query string variables this way.

    EDIT: --- Also as another poster pointed out that you have to create these properties on every page. My answer is no you do not. You can create these properties in a single class that you can call "QueryStrings" or something. Then you can instantiate this class in every page where you want to access your query strings, then you can simply do something like

    var queryStrings = new QueryStrings();
    var age = queryStrings.age;
    

    This way you can encapsulate all of the logic for accessing and handling each type of query variable in a single maintainable location.

    EDIT2: --- And because it is an instance of the class, you could also use dependency injection to inject the QueryStrings class in every place you are using it. StructureMap does a good job of that. This also allows you to mock up the QueryStrings class and inject that if you wanted to do automated unit testing. It is much easier to mock this up than ASP.Net's Request object.

提交回复
热议问题