这是我向服务器发送邮件查询的代码:
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
格式发送数据时才会起作用,当我尝试剪切自定义字符串时,他就会崩溃:"to="+value+"&from="+value+"&title="+value+"&message="+value
但是我需要从模型发送数据并获得0回答。之后PHP脚本向我发送包含数据的电子邮件。任何人都知道,如何转换json格式的对象name=value&name=value
也许我需要更改内容类型并将jsonString发送到服务器?但如果这是真的,我需要使用什么格式?
答案 0 :(得分:0)
您需要对数据进行URL编码。
"to="+value+"&from="+value+"&title="+value+"&message="+value
应更改为:
"to="+HttpUtility.UrlEncode (value)+"&from="+HttpUtility.UrlEncode(value)+"&title="+HttpUtility.UrlEncode(value)+"&message="+HttpUtility.UrlEncode (value)