【问题标题】:Not able to call WCF using ajax call无法使用 ajax 调用来调用 WCF
【发布时间】:2014-05-04 15:40:25
【问题描述】:

我是 WCF 新手并创建了一个 WCF 并将其命名为 CategoryMasterWCF.svc 文件,其中 iCategoryMasterWCF.cs 具有以下代码

namespace InfraERP.WebServices
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICategoryMasterWCF" in both code and config file together.
[ServiceContract]
public interface ICategoryMasterWCF
{
    [OperationContract]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat= WebMessageFormat.Json)]
    string DoWork();

    [OperationContract]
    [WebGet]
    [WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json)]
    string sting(int id);

}


}

CategoryMasterWCF.svc.cs 代码如下

namespace InfraERP.WebServices
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CategoryMasterWCF" in code, svc and config file together.
 [AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class CategoryMasterWCF : ICategoryMasterWCF
{

   public string DoWork()
    {
        return "Hello, It Worked! ";
    }

    public string sting(int id)
    {
        string _sting = "Number is " +id.ToString();
        return _sting;
    }

}
}

然后我在我的 aspx 中添加了如下代码

 $.ajax({
        type: "POST",
        url: '../WebServices/CategoryMasterWCF.svc/sting',
        contentType: "application/json; charset=UTF-8; charset-uf8",
        data: {id:"1"},
        processData: true,
        dataType: "json",
        success: function (msg) {
            alert(msg);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus + "---" + errorThrown);
        }
    });

出现的错误是“不支持的媒体类型”。

我不是 WCF 或 Asp.net 方面的专家。我在网上和 stackoverflow 中搜索了很多,并使用提供的更改进行了测试,但没有找到好的结果。目前我还没有对网络配置进行任何更改。请帮我找到出路。

【问题讨论】:

    标签: c# asp.net ajax wcf


    【解决方案1】:

    [WebGet] 属性在 sting 方法之上的作用是什么?您应该使用其中之一(WebGet 用于 Http GET,WebInvoke 用于其余的,默认为 POST)。由于您在您的网站中发出POST 请求,因此您可以将其删除。

    还将您发送的数据转换为 JSON 字符串:

    $.ajax({
        type: "POST",
        url: '../WebServices/CategoryMasterWCF.svc/sting',
        contentType: "application/json; charset=UTF-8; charset-uf8",
        data: JSON.stringify({id:"1"}),
        processData: true,
        dataType: "json",
        success: function (msg) {
            alert(msg);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus + "---" + errorThrown);
        }
    });
    

    【讨论】:

      【解决方案2】:

      您是否尝试从 ajax 调用中删除 contentType 和 dataType?

      【讨论】:

      • 是的,但没有帮助。:(
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 2015-04-27
      相关资源
      最近更新 更多