流不支持并发IO读取或写入操作

流不支持并发IO读取或写入操作

本文介绍了错误:流不支持并发IO读取或写入操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
/system.net.httpwebrequest.getresponse.aspxrel =nofollow> GetResponse() 会导致到目前为止建立的请求被发送,



您需要在调用 GetResponse()之前构建完整的请求,请求不会完成。在调用 GetResponse()之后获取请求流和写入POST数据将抛出此异常,以表明在已经发送请求之后继续构建请求是没有意义的。 p>

I am trying to log in to a website from my C# web application to send emails directly from the application instead of making user visit the website personally.

NOTE: The website, I am trying to log into changes the id of the textboxes everytime the page is loaded, EVEN DURING THE SAME SESSION. Therefore I decided to read the page source, extract the id of the textbox and then use that id while posting the message.

public partial class sender : System.Web.UI.Page
{
    string userID, userPwd, recepsID, msgText, loginResponseString, sessionCode, queryCode;
    private HttpWebRequest initRequest, loginRequest, msgRequest;
    private HttpWebResponse initResponse, loginResponse;
    private Object lockObj = new Object();

    protected void Page_Load(object sender, EventArgs e)
    {
        userID = Request.QueryString["userNumber"];
        userPwd = Request.QueryString["userPwd"];
        recepsID = Request.QueryString["receps"];
        msgText = Request.QueryString["msgBody"];
        if (userID != null && userPwd != null && recepsID != null & msgText != null)
            doLoginAndSendMessage(userID, userPwd, recepsID, msgText);
        else
            Response.Write("Some values are missing");
    }

    public void doLoginAndSendMessage(string uid, string pwd, string recepIds, string msg)
    {
        try
        {
            doLogin(uid, pwd, recepIds, msg);
        }
        catch (Exception ex)
        {
            Response.Write("Sending Failed, Please Try Again");
        }
    }

    public void doLogin(string strUserId, string strPassword, string strIds, string strMessage)
    {
        try
        {
            initRequest = (HttpWebRequest)WebRequest.Create("http://www.somewebsite.com/login.aspx");
            initRequest.CookieContainer = new CookieContainer();
            initRequest.Timeout = 60000;
            StreamReader initSr = new StreamReader(initRequest.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
            initSr.ReadToEnd();
            initSr.Close();

            loginRequest = (HttpWebRequest)WebRequest.Create("http://www.somewebsite.com/login.aspx");
            loginRequest.CookieContainer = new CookieContainer();
            loginRequest.Timeout = 60000;
            StringBuilder loginString = new StringBuilder();
            loginString.Append("LoginUserId=" + strUserId + "&LoginPassword=" + strPassword + "&RememberMe=1&Login=Login");
            byte[] loginData = Encoding.ASCII.GetBytes(loginString.ToString());
            //to get any cookies from the initial response
            initResponse = (HttpWebResponse)initRequest.GetResponse();
            //setting cookies
            loginRequest.CookieContainer.Add(initResponse.Cookies);
            //Adding Headers
            loginRequest.Method = "POST";
            loginRequest.ContentType = "application/x-www-form-urlencoded";
            loginRequest.ContentLength = loginData.Length;
            Stream loginStream = loginRequest.GetRequestStream();
            loginStream.Write(loginData, 0, loginData.Length);
            loginStream.Close();

            //Reading the response
            StreamReader loginSr = new StreamReader(loginRequest.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
            loginResponseString = loginSr.ReadToEnd();
            loginSr.Close();

            if (loginResponseString.Contains("inbox.aspx"))
            {
                //get session code
                sessionCode = loginResponseString.Substring(125, 5);
                //call the sendmessage method
                sendMessage(strIds, strMessage);

            }
            else
            {
                Response.Write("Login Failed: Check Username and password");
            }
        }
        catch (Exception ex)
        {
            Response.Write("Sending Failed, Please Try Again");
        }
    }

    public void sendMessage(string strIds, string strMsg)
    {
        try
        {
            string[] ids = strIds.Split(',');
            for (int i = 0; i < ids.Length; i++)
            {
                msgRequest = (HttpWebRequest)WebRequest.Create("http://www.somewebsite.com/writenew.aspx?sessionid=" + sessionCode);
                msgRequest.CookieContainer = new CookieContainer();
                msgRequest.Timeout = 1000000;
                msgRequest.ReadWriteTimeout = 1000000;
                msgRequest.SendChunked = true;
                //to get any cookies from the initial response
                loginResponse = (HttpWebResponse)loginRequest.GetResponse();
                //setting cookies
                msgRequest.CookieContainer.Add(loginResponse.Cookies);
                //Adding Headers
                msgRequest.Method = "POST";
                msgRequest.ContentType = "application/x-www-form-urlencoded";

                Stream msgStream = msgRequest.GetRequestStream();

                Stream respStream = msgRequest.GetResponse().GetResponseStream();

                StreamReader codeRead = new StreamReader(respStream, System.Text.Encoding.GetEncoding("utf-8"));
                string temp = codeRead.ReadToEnd();
                codeRead.Close();
                respStream.Close();
                txtResponse.Text = temp;

                try
                {
                    int starInd = temp.IndexOf("UserId_");
                    //int endInd = starInd + 15;
                    string holder = temp.Substring(starInd, 15);
                    int startInd = holder.IndexOf("_") + 1;
                    queryCode = holder.Substring(startInd, 5);
                    txtSubString.Text = queryCode;
                }
                catch (Exception ex)
                {
                    txtSubString.Text = "SOME ERROR";
                }

                lock (lockObj)
                {
                    StringBuilder msgString = new StringBuilder();
                    msgString.Append("sessionid=" + queryCode + "&GlobalKeyId=1&MessageLength=988&ReceiveId_"
                        + queryCode + "=" + ids[i] + "&Message_" + queryCode + "=" + strMsg
                        + "&SendNow_" + queryCode + "=Send Now");
                    byte[] msgData = Encoding.ASCII.GetBytes(msgString.ToString());
                    msgStream.Write(msgData, 0, msgData.Length);
                    msgStream.Close();
                }

                //Reading the response
                StreamReader msgSr = new StreamReader(respStream, System.Text.Encoding.GetEncoding("utf-8"));
                string msgResponseString = msgSr.ReadToEnd();
                msgSr.Close();
                sessionCode = msgResponseString.Substring(123, 5);
            }
            Response.Write("Message Sent Successfully");
        }
        catch (Exception ex)
        {
            Response.Write("Sending Failed, Please Try Again<br/>" + ex.Message);
        }
    }
}

The application stops when it reaches this line

msgStream.Write(msgData, 0, msgData.Length);

Please help me solve the error. Thank You

解决方案

When you call GetResponse() it will cause the request built so far to be sent, and the client to fetch the response.

You need to build your complete request before calling GetResponse(), or your request won't be complete. Getting the request stream and writing POST data after GetResponse() was called will throw this exception to show that continuing building the request after it has already been sent makes no sense.

这篇关于错误:流不支持并发IO读取或写入操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 17:32