我正在将ajax发布到webmethod EmailFormRequestHandler上,我可以在客户端(通过Firebug)看到请求的状态为200,但未达到Webmethod中的停止点(webmethod的第一行)。 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":"[email protected]","from":"[email protected]","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存档:Using jQuery to directly call ASP.NET AJAX page methods

  • 您无需将ScriptManager配置为EnablePageMethods。

    另外,您无需在WebMethod中反序列化JSON序列化的对象。让ASP.NET为您做到这一点。将您的WebMethod的签名更改为this(注意,我在单词“to”和“from”之后附加了“Email”,因为它们是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/

    10-10 08:52