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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8946695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:20:46  来源:igfitidea点击:

passing json string as parameter to webmethod

c#javascriptjqueryajax

提问by bflemi3

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 objectbut with the way that I'm deserializing the json I had to change it to a string.

我正在向 webmethod 发送 ajax 帖子EmailFormRequestHandler,我可以在客户端(通过萤火虫)看到请求的状态是 200,但它没有到达我的 webmethod 中的停止点(webmethod 的第一行)。使用 json 参数一切正常,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":"[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:

ASP:

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

采纳答案by Mario J Vargas

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. 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:

此外,您不需要在 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;
    }
}

回答by Sven Bieder

You mean you want to set a break point? Don't set that point in firebug. Set that breakpoint in VS itself. Then attach VS to local IIS.

你是说要设置断点?不要在萤火虫中设置那个点。在 VS 本身中设置该断点。然后将 VS 附加到本地 IIS。

By the way, in your ajax call you set three parameter, your webmethod takes only one. and the parameter name must be the same.

顺便说一下,在你的 ajax 调用中你设置了三个参数,你的 webmethod 只需要一个。并且参数名称必须相同。

The format of your data attribute in the ajax call is also not good. It should look like this

ajax 调用中数据属性的格式也不好。它应该是这样的

data: '{"to":"[email protected]","from":"[email protected]","message":"sdfasdf"}',

it should be framed in ' '

它应该被框在' '

回答by Cam

First thing I noticed is that you are missing contentType: "application/json; charset=utf-8" in your $.ajax. Also addd to your $.ajax a complete callback it returns jqXHR,textStatus. I think the complete callback will help because textStatus one of the following ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). This might help you track down the issue.

我注意到的第一件事是您的 $.ajax 中缺少 contentType: "application/json; charset=utf-8"。还向您的 $.ajax 添加一个完整的回调,它返回 jqXHR,textStatus。我认为完整的回调会有所帮助,因为 textStatus 是以下之一(“成功”、“未修改”、“错误”、“超时”、“中止”或“解析器错误”)。这可能会帮助您追踪问题。

回答by Антон Бесхмельницкий

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.

当前端首先出现时,我在调试时使用它。