简体   繁体   English

将json字符串作为参数传递给webmethod

[英]passing json string as parameter to webmethod

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. 我正在向webmethod EmailFormRequestHandler一个ajax帖子,我可以在客户端(通过firebug)看到请求的状态是200但是它没有达到我的webmethod中的停止点(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. 一切都工作得很好,json param是一个object但是我正在反序列化json的方式我必须把它改成一个字符串。

js: 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: 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: 你错过了jQuery JSON帖子中的内容类型:

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

See this article. 看到这篇文章。 It helped me greatly when I had a similar issue: 当我遇到类似问题时,它对我帮助很大:

You don't need to configure the ScriptManager to EnablePageMethods. 您无需将ScriptManager配置为EnablePageMethods。

Also, you don't need to deserialize the JSON-serialized object in your WebMethod. 此外,您不需要在WebMethod中反序列化JSON序列化对象。 Let ASP.NET do that for you. 让ASP.NET为您做到这一点。 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: 将WebMethod的签名更改为此(注意我将“Email”附加到单词“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;
    }
}

May be this code helps someone: 可能是这段代码可以帮助某人:

public Dictionary<string, object> JsonToDictionary(dynamic request)
{
JObject x = JObject.FromObject(request);
Dictionary<string, object> result = new Dictionary<string, object>();

foreach (JProperty prop in (JContainer)x)
    { 
       result.Add(prop.Name, prop.Value);
    }

return result;
}

I use it while debuging when frontend comes first. 当前端出现时,我在使用它时进行调试。

You mean you want to set a break point? 你的意思是你想设置一个断点? Don't set that point in firebug. 不要在萤火虫中设置这一点。 Set that breakpoint in VS itself. 在VS本身设置断点。 Then attach VS to local IIS. 然后将VS附加到本地IIS。

By the way, in your ajax call you set three parameter, your webmethod takes only one. 顺便说一下,在你的ajax调用中你设置了三个参数,你的webmethod只需要一个。 and the parameter name must be the same. 并且参数名称必须相同。

The format of your data attribute in the ajax call is also not good. ajax调用中数据属性的格式也不好。 It should look like this 它看起来应该是这样的

data: '{"to":"bfleming@allegisgroup.com","from":"bfleming@test.com","message":"sdfasdf"}',

it should be framed in ' ' 它应该用''框起来

First thing I noticed is that you are missing contentType: "application/json; charset=utf-8" in your $.ajax. 我注意到的第一件事是你在$ .ajax中缺少contentType:“application / json; charset = utf-8”。 Also addd to your $.ajax a complete callback it returns jqXHR,textStatus. 还要在$ .ajax中添加一个完整的回调函数,它返回jqXHR,textStatus。 I think the complete callback will help because textStatus one of the following ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). 我认为完整的回调将有所帮助,因为textStatus是以下之一(“成功”,“未修改”,“错误”,“超时”,“中止”或“parsererror”)。 This might help you track down the issue. 这可能有助于您追踪问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM