C# 如何从ajax调用WCF服务?
我有一个WCF服务,如下所示-C# 如何从ajax调用WCF服务?,c#,asp.net,ajax,wcf,C#,Asp.net,Ajax,Wcf,我有一个WCF服务,如下所示- [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Sync { [OperationContract] [WebInvoke] public string SyncDataNow(UserData ob
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Sync
{
[OperationContract]
[WebInvoke]
public string SyncDataNow(UserData obj)
{
try
{
using (MavenifyEntities db = new MavenifyEntities())
{
bool userExist = db.Users.Any(u => u.Id == obj.UserId);
if (userExist)
{
DataSync data = new DataSync();
data.UserId = obj.UserId;
data.TempId = obj.TempId;
data.Content = obj.Content;
data.CreatedDate = DateTime.Now.ToString();
db.DataSyncs.Add(data);
db.SaveChanges();
return "1";
}
else
{
return "0";
}
}
}
catch (Exception ex)
{
return "error";
}
}
}
[DataContract(Namespace = "")]
public class UserData
{
[DataMember]
public int UserId { get; set; }
[DataMember]
public string Content { get; set; }
[DataMember]
public string TempId { get; set; }
}
当我从邮递员处呼叫此服务时,它接收到空数据,请帮助我找出我所做的错误
我以json格式发送原始数据,如-
{“UserData”:{“UserId”:“1”,“TempId”:“asdbsjiadf”,“Content”:“Hello”}
我的web.config条目是-
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="PhoneSync.SyncAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="PhoneSync.Sync">
<endpoint address="" behaviorConfiguration="PhoneSync.SyncAspNetAjaxBehavior" binding="webHttpBinding" contract="PhoneSync.Sync" />
</service>
</services>
您应该使用Wcf Rest
WebHttpBinding
并且您将面临跨域消息传递问题。因此,您将禁用交叉消息传递安全性或为jsonp创建自己的行为
另外,您的消息应该是{“UserId”:“1”,“TempId”:“asdbsjiadf”,“Content”:“Hello”}
以供您签名。
如果你想使用{“UserData”:{“UserId”:“1”,“TempId”:“asdbsjiadf”,“Content”:“Hello”}}
你应该包装它确保请求/响应默认为Json。我将在[WebInvoke(RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)]中明确指定这一点
也许配置一些选项是有意义的我已经解决了这个问题,将json中的“UserData”改为“obj”,即
{“UserData”:{“UserId”:“1”,“TempId”:“asdbsjiadf”,“Content”:“Hello”}
到
{“obj”:{“UserId”:“1”,“TempId”:“asdbsjiadf”,“Content”:“Hello”}
现在我正在我的服务中接收数据。但我无法理解为什么会发生这种情况。请分享原因。确保请求/响应默认为json。我将在[WebInvoke(RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)]中明确指定这一点