天天看點

Asp.net中程式設計方式調用ashx(通過webRequest)

請看代碼:

    public sealed string GetGscCurrentUser()

    {

        HttpWebRequest webRequest = null;

        StreamReader responseReader = null;

        try

        {

            //ashx Url

            string getGscUserUrl = "http:/xxx.com/GscHandler.ashx";

            //加入參數,用于更新請求

            string urlHandler = getGscUserUrl + "?id=" + Guid.NewGuid();            

            webRequest = (HttpWebRequest)HttpWebRequest.Create(urlHandler);

            webRequest.Timeout = 3000;//3秒逾時

            //調用ashx,并取值

            responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());

            string currentUserGulid = responseReader.ReadToEnd();

            return currentUserGulid.Trim();

        }

        catch

            return "";

        finally

            responseReader.Close();

            responseReader.Dispose();

    }

 需要授權時寫法如下:

        public string GetGscCurrentUser()

            HttpWebRequest webRequest = null;

            StreamReader responseReader = null;

            try

            {

                string getGscUserUrl = System.Configuration.ConfigurationManager.AppSettings["GscGetUserUrl"];

                string urlHandler = getGscUserUrl + "?id=" + Guid.NewGuid();

                webRequest = (HttpWebRequest)HttpWebRequest.Create(urlHandler);

                webRequest.Timeout = 3000;//3秒逾時

                webRequest.PreAuthenticate = true;

                NetworkCredential gscCred = new NetworkCredential("account", "***");

                webRequest.Credentials = gscCred;

                responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());

                string currentUserGulid = responseReader.ReadToEnd();

                return currentUserGulid.Trim();

            }

            catch

                return "";

            finally

                responseReader.Close();

                responseReader.Dispose();