简体   繁体   English

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

[英]error: The stream does not support concurrent IO read or write operations

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. 我正在尝试从C#Web应用程序登录到网站,以直接从该应用程序发送电子邮件,而不是让用户亲自访问该网站。

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. 注意:网站,每次尝试加载页面时,我都尝试登录更改textboxesid ,即使在同一会话期间也是如此。 Therefore I decided to read the page source, extract the id of the textbox and then use that id while posting the message. 因此,我决定阅读页面源代码,提取文本框的id ,然后在发布消息时使用该id

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. 当您调用GetResponse() ,它将导致发送到目前为止已建立的请求,并且客户端将获取响应。

You need to build your complete request before calling GetResponse() , or your request won't be complete. 您需要在调用GetResponse()之前构建完整的请求,否则您的请求将不完整。 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. 在调用GetResponse()之后获取请求流并写入POST数据将引发此异常,以表明在已发送请求后继续构建请求是没有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM