从请求后的答案中得不到0

时间:2017-07-10 17:08:19

标签: c# asp.net json post request

我需要发送电子邮件,感谢php脚本。服务器中的Sript,我确实向服务器发送了请求,并得到了答案。如果一切都好,我会得0,如果我得到1,那一切都很糟糕。

这是我的代码:

public class MessagePost
{
    public string to { get; set; }
    public string from { get; set; }
    public string title { get; set; }
    public string message { get; set; }
}

[HttpPost]
    public ActionResult SendMessage(FEEDBACK feedbackModel)
    {
        try
        {
            string FromEmail = feedbackModel.sEmail;
            string toEmail = "zicise@mail.ru";
            string title = "Сообщение с сайта народный комунальщик от " + feedbackModel.vFIO;
            string message = feedbackModel.vMessage;

            MessagePost MP = new MessagePost();

            MP.to = toEmail;
            MP.from = FromEmail;
            MP.title = title;
            MP.message = message;

            List<MessagePost> dataMessage = new List<MessagePost>();

            dataMessage.Add(MP);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string json = serializer.Serialize(dataMessage);

            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("http://projects.pushnovn.com/send_email/");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = json;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

            string convertResult = System.Text.Encoding.UTF8.GetString(byteArray);

            RootObject r = JsonConvert.DeserializeObject<RootObject>(responseFromServer);

            if (r.code == 0)
            {
                ViewBag.RedirectMessage = r.msg;
                return View("~/Views/Home/RedirectPage.cshtml");
            }
            else
            {
                ViewBag.RedirectMessage = r.msg;
                return View("~/Views/Home/RedirectPage.cshtml");
            }
        }
        catch (Exception exc)
        {
            ViewBag.RedirectMessage = "Невозможно отправить e-mail - error: " + exc.Message;
            return View("~/Views/Home/RedirectPage.cshtml");
        }
    }

但我总是得到1,出了什么问题?

E.g。数据

to:zicise@mail.ru

来自:test@mail.ru

标题:测试题目

消息:测试消息

1 个答案:

答案 0 :(得分:0)

好的。所以,我做到了。但不是我想要的。这是我发送邮件查询到服务器的代码:

public static HttpWebResponse PostMethod(string postedData, string postUrl)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
        request.Method = "POST";
        request.Credentials = CredentialCache.DefaultCredentials;

        UTF8Encoding encoding = new UTF8Encoding();
        var bytes = encoding.GetBytes(postedData);

        //request.ContentType = "application/javascript";
        request.ContentType = "application/x-www-form-urlencoded";
        //request.ContentType = "application/json; charset=utf-8";
        //request.ContentType = "application/json";
        //request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

        request.ContentLength = bytes.Length;

        using (var newStream = request.GetRequestStream())
        {
            newStream.Write(bytes, 0, bytes.Length);
            newStream.Close();
        }
        return (HttpWebResponse)request.GetResponse();
    }

和ActionResult:

[HttpPost]
    public ActionResult SendMessage(FEEDBACK feedbackModel)
    {
        MessageData msgData = new MessageData();

        msgData.to = "zicise@mail.ru";
        msgData.from = feedbackModel.sEmail;
        msgData.title = "Сообщение с сайта наркома от пользователя: " + feedbackModel.vFIO;
        msgData.message = feedbackModel.vFIO;

        var jsonString = JsonConvert.SerializeObject(msgData);

        var response = PostMethod("to=zicise@mail.ru&from=narkom@info.by&title=Second method&message=test message", "http://projects.pushnovn.com/send_email/");
        //var response = PostMethod("to:zicise@mail.ru,from:narkom@info.by,title:Second method,message:test message", "http://projects.pushnovn.com/send_email/");
        //var response = PostMethod("{to:zicise@mail.ru,from:narkom@info.by,title:Second method,message:test message}", "http://projects.pushnovn.com/send_email/");
        //var response = PostMethod("[{to:zicise@mail.ru,from:narkom@info.by,title:Second method,message:test message}]", "http://projects.pushnovn.com/send_email/");
        //var response = PostMethod(jsonString, "http://projects.pushnovn.com/send_email/");

        if (response != null)
        {
            var strreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            var responseToString = strreader.ReadToEnd();

            RootObject r = JsonConvert.DeserializeObject<RootObject>(responseToString);

            ViewBag.RedirectMessage = r.msg;
        }

        return View("~/Views/Home/RedirectPage.cshtml");
    }

但是这段代码只有在我以格式发送数据时才有效:to=zicise@mail.ru&from=narkom@info.by&title=Second method&message=test message

但是我需要从模型发送数据并获得0回答。之后PHP脚本向我发送包含数据的电子邮件。任何人都知道,如何转换json格式的对象name=value&name=value