X龙@China .Net 'blog

需要的不仅仅是工作,而是通过努力得来的美好将来。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

在后台获取ashx返回的数据

Posted on 2011-06-02 11:53  X龙  阅读(3008)  评论(4编辑  收藏  举报
public static string GetRequestJsonString(string relativePath, string data)
    {
        
string requestUrl = GetRequestUrl(relativePath, data);

        
try
        {
            WebRequest request 
= WebRequest.Create(requestUrl);
            request.Method 
= "GET";

            StreamReader jsonStream 
= new StreamReader(request.GetResponse().GetResponseStream());
            
string jsonObject = jsonStream.ReadToEnd();

            
return jsonObject;
        }
        
catch 
        {
            
return  string.Empty;
        }        
    }

 

补充:    public static string GetRequestUrl(string relativePath, string data)

    {
        
string absolutePath = HttpContext.Current.Request.Url.AbsoluteUri;
        
string hostNameAndPort = HttpContext.Current.Request.Url.Authority;
        
string applicationDir = HttpContext.Current.Request.ApplicationPath;
        StringBuilder sbRequestUrl 
= new StringBuilder();

        sbRequestUrl.Append(absolutePath.Substring(
0, absolutePath.IndexOf(hostNameAndPort)));
        sbRequestUrl.Append(hostNameAndPort);
        sbRequestUrl.Append(applicationDir);
        sbRequestUrl.Append(relativePath);

        
if (!string.IsNullOrEmpty(data))
        {
            sbRequestUrl.Append(
"?");
            sbRequestUrl.Append(data);
        }

        
return sbRequestUrl.ToString();

    } 

 使用示例:string strData= "pageIndex=1&pageSize=15";            

        string strResult = GetRequestJsonString("ashx/SearchProduct.ashx", strData);

 

点击这里给我发消息http://wp.qq.com/index.html