我正在向 webmethod EmailFormRequestHandler
发送 ajax post,我可以在客户端(通过 Firebug )看到请求的状态是 200,但它没有到达停止点(第一行网络方法)在我的网络方法中。 json 参数是一个 object
一切正常,但由于我反序列化 json 的方式,我不得不将其更改为字符串。
js:
function SubmitUserInformation($group) {
var data = ArrayPush($group);
$.ajax({
type: "POST",
url: "http://www.example.com/components/handlers/FormRequestHandler.aspx/EmailFormRequestHandler",
data: JSON.stringify(data), // returns {"to":"bfleming@allegisgroup.com","from":"bfleming@test.com","message":"sdfasdf"}
dataType: 'json',
cache: false,
success: function (msg) {
if (msg) {
$('emailForm-content').hide();
$('emailForm-thankyou').show();
}
},
error: function (msg) {
form.data("validator").invalidate(msg);
}
});
}
aspx:
[WebMethod]
public static bool EmailFormRequestHandler(string json)
{
var serializer = new JavaScriptSerializer(); //stop point set here
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic obj = serializer.Deserialize(json, typeof(object));
try
{
MailMessage message = new MailMessage(
new MailAddress(obj.to),
new MailAddress(obj.from)
);
message.Subject = "email test";
message.Body = "email test body" + obj.message;
message.IsBodyHtml = true;
new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]).Send(message);
return true;
}
catch (Exception e)
{
return false;
}
}
最佳答案
您在 jQuery JSON 帖子中缺少内容类型:
contentType: "application/json; charset=utf-8",
请参阅这篇文章。当我遇到类似问题时,它对我帮助很大:
Using jQuery to directly call ASP.NET AJAX page methods(不再可用)- 来自 Internet Archive: Using jQuery to directly call ASP.NET AJAX page methods
您不需要将 ScriptManager 配置为 EnablePageMethods。
此外,您不需要在 WebMethod 中反序列化 JSON 序列化对象。让 ASP.NET 为您做这件事。将您的 WebMethod 的签名更改为此(注意到我将“电子邮件”附加到“to”和“from”这两个词,因为这些是 C# 关键字,并且命名与关键字相同的变量或参数是一种不好的做法。你将需要相应地更改您的 JavaScript,以便 JSON.stringify() 正确序列化您的字符串:
// Expected JSON: {"toEmail":"...","fromEmail":"...","message":"..."}
[WebMethod]
public static bool EmailFormRequestHandler(string toEmail, string fromEmail, string message)
{
// TODO: Kill this code...
// var serializer = new JavaScriptSerializer(); //stop point set here
// serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
// dynamic obj = serializer.Deserialize(json, typeof(object));
try
{
var mailMessage = new MailMessage(
new MailAddress(toEmail),
new MailAddress(fromEmail)
);
mailMessage.Subject = "email test";
mailMessage.Body = String.Format("email test body {0}" + message);
mailMessage.IsBodyHtml = true;
new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]).Send(mailMessage);
return true;
}
catch (Exception e)
{
return false;
}
}
关于c# - 将 json 字符串作为参数传递给 webmethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8946695/