通过JSON字符串作为参数的WebMethod字符串、参数、JSON、WebMethod

2023-09-10 21:17:31 作者:宁负苍天不负你°

我在做一个ajax后,以一个WebMethod EmailFormRequestHandler ,我可以看到在客户端(通过萤火虫)请求的状态是200,但它不打止损点(WebMethod的第一行)在我的WebMethod。一切工作正常使用json参数是一个对象,但与我反序列化JSON我不得不将其更改为一个字符串的方式。

记者:

 函数SubmitUserInformation($组){
    VAR数据= ArrayPush($组);
    $阿贾克斯({
        键入:POST,
        网址:http://www.example.com/components/handlers/FormRequestHandler.aspx/EmailFormRequestHandler
        数据:JSON.stringify(数据),//返回{到:bfleming@allegisgroup.com,从:bfleming@test.com,消息:sdfasdf}
        数据类型:JSON,
        缓存:假的,
        成功:函数(MSG){
            如果(MSG){
                $('emailForm内容)隐藏();
                $('emailForm  - 三江源)显示();
            }
        },
        错误:函数(MSG){
            。form.data(验证)无效(MSG);
        }
    });
}
 

ASPX:

  [WebMethod的]
公共静态布尔EmailFormRequestHandler(JSON字符串)
{
    无功序列化=新JavaScriptSerializer(); //此处止损点设置
    serializer.RegisterConverters(新[] {新DynamicJsonConverter()});
    动态OBJ = serializer.Deserialize(JSON的typeof(对象));

    尝试
    {
        MailMessage消息=新MailMessage(
            新MailAddress(obj.to)
            新MailAddress(obj.from)
        );
        message.Subject =电子邮件测试;
        message.Body =电子邮件检测机构+ obj.message;
        message.IsBodyHtml = TRUE;
        新的SmtpClient(ConfigurationManager.AppSettings [SMTPSERVER])发送(消息)。
        返回true;
    }
    赶上(例外五)
    {
        返回false;
    }
}
 

解决方案 怎样在C 中使用json字符串

您错过了jQuery的JSON帖子的内容类型:

 的contentType:应用/ JSON的;字符集= UTF-8,
 

请参阅这篇文章。它帮了我很大的,当我有一个类似的问题:

使用jQuery直接调用ASP.NET AJAX页面的方法

您并不需要配置的ScriptManager到的EnablePageMethods。

另外,你不需要反序列化的JSON序列化对象在你的WebMethod。让ASP.NET为你做的。改变你的WebMethod本的签名(注意到我追加电子邮件的话到和从,因为这是C#的关键字,这是一个不好的做法来命名变量或参数是相同的关键字。您需要相应地改变你的JavaScript所以JSON.stringify()将正确序列化字符串:

  //预期的JSON:{toEmail:......,fromEmail:......,消息:...}

[WebMethod的]
公共静态布尔EmailFormRequestHandler(字符串toEmail,串fromEmail,字符串消息)
{
    // TODO:杀死这个code ...
    //无功序列化=新JavaScriptSerializer(); //此处止损点设置
    // serializer.RegisterConverters(新[] {新DynamicJsonConverter()});
    //动态OBJ = serializer.Deserialize(JSON的typeof(对象));

    尝试
    {
        VAR mailMessage =新MailMessage(
            新MailAddress(toEmail)
            新MailAddress(fromEmail)
        );
        mailMessage.Subject =电子邮件测试;
        mailMessage.Body =的String.Format(电子邮件检测机构{0}+消息);
        mailMessage.IsBodyHtml = TRUE;
        新的SmtpClient(ConfigurationManager.AppSettings [SMTPSERVER])发送(mailMessage)。
        返回true;
    }
    赶上(例外五)
    {
        返回false;
    }
}
 

I'm making an ajax post to a webmethod EmailFormRequestHandler, I can see on the client side (through firebug) that status of the request is 200 but it's not hitting the stop point (first line of the webmethod) in my webmethod. Everything was working fine with the json param was an object but with the way that I'm deserializing the json I had to change it to a string.

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;
    }
}

解决方案

You're missing the content type in the jQuery JSON post:

contentType: "application/json; charset=utf-8",

See this article. It helped me greatly when I had a similar issue:

Using jQuery to directly call ASP.NET AJAX page methods

You don't need to configure the ScriptManager to EnablePageMethods.

Also, you don't need to deserialize the JSON-serialized object in your WebMethod. Let ASP.NET do that for you. Change the signature of your WebMethod to this (noticed that I appended "Email" to the words "to" and "from" because these are C# keywords and it's a bad practice to name variables or parameters that are the same as a keyword. You will need to change your JavaScript accordingly so the JSON.stringify() will serialize your string correctly:

// 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;
    }
}