从JQuery发布到WCF服务 [英] Posting from JQuery to WCF Service

查看:101
本文介绍了从JQuery发布到WCF服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WCF服务(称为"myservice.svc"),该服务接收来自用户的消息并将其保存到数据库中.它以数字形式向用户返回响应.此操作如下所示:

I have a WCF Service (called "myservice.svc") that takes a message from a user and saves it to the database. It returns a response to the user in the form of a number. This operation looks like this:

[OperationContract]
[WebGet]
public string SubmitMessage(string message)
{
  try
  {
    // SAVE TO DATABASE
    return "1";
  }
  catch (Exception ex)
  {
    return "0";
  }
}

我想从某些JQuery调用此操作.我正在使用此处显示的方法:

I want to call this operation from some JQuery. I'm using the approach shown here:

$.getJSON(
  "/services/myService.svc",
  {message:"some text"},
  function (data) {
    alert("success");                
  }
);

奇怪的是,永远不会显示成功"警报.另外,我已经在WCF服务中设置了一个断点,并且它从未被触发过.我在做什么错了?

Oddly, the "success" alert is never displayed. In addition, I have set a breakpoint in my WCF service and it is never being tripped. What am I doing wrong?

谢谢

推荐答案

WebGet不应该存在,并且您不应该使用jQuery getJSON函数.此方法修改数据库;这是一个POST方法,而不是GET.

That WebGet shouldn't be there, and you shouldn't be using the jQuery getJSON function. This method modifies the database; it is a POST method, not GET.

有关创建此页面 >方法.主要是将这些标头添加到方法中:

See this page for an example of creating a POST method. Mainly it involves adding these headers to the method:

[OperationContract]          
[WebInvoke(Method = "POST",
           BodyStyle = WebMessageBodyStyle.Wrapped,
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json)]

您还需要确保从jQuery正确进行调用,其中包括设置contentType和其他字段;进行呼叫的方式实际上是无效的,您只是将原始文本传递给该方法,而不是有效的查询字符串或有效的JSON.

You also need to make sure that you make the call correctly from jQuery, which includes setting the contentType and other fields; the way you're making the call actually isn't valid, you're just passing raw text to the method, not a valid query string or valid JSON.

此外,您使用了错误的URL;您不想发布到端点,需要发布到特定方法,必须将其附加到URL.同样,链接的页面应有助于解释所有这些情况.

Also, you're using the wrong URL; you don't want to be posting to the endpoint, you need to post to the specific method, you have to append that to the URL. Again, the linked page should help explain all of this.

这是一个正确的jQuery Ajax帖子的示例:

Here's an example of a correct jQuery Ajax post:

$.ajax({ 
    url: "/services/myservice.svc/SubmitMessage",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: "{ \"message\": \"test\" }",
    dataType: "json",
    success: function(data) {
        // do something
    }
});

这篇关于从JQuery发布到WCF服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆