2014-03-26 27 views
0

我是新來的WCF並創建了一個WCFand命名爲CategoryMasterWCF.svc具有下列代碼無法使用WCF Ajax調用

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 iCategoryMasterWCF.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中進行了搜索,並且測試了所提供的更改,但沒有找到好的結果。目前我還沒有在網絡配置上做任何改變。請幫我找到一條出路。

回答

0

您是否嘗試從ajax調用中移除contentType和dataType?

+0

是,但它並沒有幫助:( – Farook

+0

您可以發佈Web.config中的代碼。 – Shanky

0

sting方法以上的屬性[WebGet]是什麼?您應該使用其中一個(默認情況下,使用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); 
    } 
});