C#WebService发送标准的post请求体,用JSON响应

时间:2012-03-29 11:50:19

标签: c# .net ajax json web-services

我在为.NET WebServices制作动态AJAX表单子方法时遇到了困难。

这个想法是发送一个从表单中的所有输入动态构建的请求。然后让服务器用JSON响应。

在提交表单时调用它,它使用索引作为输入字段名称并将值作为值填充数组:

var params = [];

for( var i in inputs )
{
    if( inputs[i].type == 'text' || inputs[i].type == 'password' )
    {
        params[inputs[i].name] = inputs[i].value;
    }
}

当发送AJAX请求时,我运行一个循环来生成请求正文:

var l = 0;
for( var i in parameters )
{
    this.parameters += ( l > 0 ? '&' : '') + i + '=' + parameters[i];
    l++;
}

给出了这样的结果:

foo=bar&lol=haha

问题是脚本servicse只接受JSON作为请求体,因为装饰器:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

我希望它返回一个JSON字符串而不是XML。

有简单的解决方案吗?

3 个答案:

答案 0 :(得分:1)

我想出的解决方案是一个相当复杂的工作,应该是简单的事情。基本上我做了一个接受Xml格式的函数。然后将数据添加到更新模型,该模型使用客户端轮询的更新方法格式化为JSON。

以下是一个例子:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class JsonHTTPService : System.Web.Services.WebService
{
    static JavaScriptSerializer JSON = new JavaScriptSerializer();

    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public dynamic update()
    {
        if (Session["user"] == null)
        {
            Session.Add("user", new User());
        }

        User user = (User)Session["user"];
        user.responseModel = new ResponseModel();

        if (user.updateListeners.Count > 0)
        {
            foreach (var updateMethod in user.updateListeners)
            {
                updateMethod.run();
            }
            return JSON.Serialize(user.responseModel);
        }
        return null;
    }

    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
    public void login(string email, string password)
    {
        if (Session["user"] == null)
        {
            return;
        }

        User user = (User)Session["user"];
        if (user.logged)
        {
            return;
        }

        if (user.Authenticate(email,password))
        {
            user.logged = true;
            user.updateListeners.Add(new LoginScreenRemover());
        }
    }
}

答案 1 :(得分:0)

试试这个

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

我在我的应用程序中尝试了同样的方法并且它有效。希望它也可以解决你的问题。

答案 2 :(得分:0)

试试这个JSON.stringify(params);