无法使用ajax调用调用WCF

时间:2014-03-26 10:08:16

标签: c# asp.net ajax wcf

我是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中进行了大量搜索,并使用提供的更改进行了测试,但未发现任何好结果。目前我还没有对网络配置进行任何更改。请帮我找个出路。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

[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);
    }
});
相关问题