Converting/accessing QueryString values in ASP.NET

后端 未结 7 1587
长情又很酷
长情又很酷 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:33

    We've been using constants to keep all of these "loose" keys in a central location:

    public class Constants
    {
      public class QueryString
      {
        public const string PostID = "pid";
        public const string PostKey = "key";
      }
      public class Cookie
      {
        public const string UserID = "mydomain.com-userid";
      }
      public class Cache
      {
        public const string PagedPostList = "PagedPostList-{0}-{1}";
      }
      public class Context
      {
        public const string PostID = "PostID";
      }
      public class Security
      {
        public const RoleAdministrator = "Administrator";
      }
    }
    

    That way, you easily access the constants you need with:

    public void Index()
    {
      if (Request[Constants.QueryString.PostKey] == "eduncan911")
      {
        // do something
      }
    }
    
    public object GetPostsFromCache(int postID, int userID)
    {
      String cacheKey = String.Format(
          Constants.Cache.PagedPostList
          , userID
          , postID);
      return Cache[cacheKey] as IList<Post>;
    }
    
    0 讨论(0)
提交回复
热议问题