我尝试了以下示例:http : //www.c-sharpcorner.com/UploadFile/surya_bg2000/developing-wcf-restful-services-with-get-and-post-methods/。
GET方法工作完美,但POST方法却不完美。调试时,strReturnValue变量始终为空。当我继续时,状态为:405方法不允许。我究竟做错了什么?
在C#中,我不得不将Method从POST更改为OPTIONS。
我正在使用Restangular(angular js)。这是前端功能:
var message = {
Name: new_player.name,
Created: (new Date()).toJSON(),
Affilation: new_player.human,
auth: new_player.auth
}
return Restangular.one('').post('CreatePlayer', message).then(function(){
console.log("Object saved OK");
}, function() {
console.log("There was an error saving");
});
编辑
[System.ServiceModel.OperationContract]
[System.ServiceModel.Web.WebInvoke(UriTemplate = "CreatePlayer", Method = "OPTIONS", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string CreatePlayer(System.IO.Stream data);
public string CreatePlayer(System.IO.Stream data) {
//convert stream data to StreamReader
System.IO.StreamReader reader = new System.IO.StreamReader(data);
//read StreamReader data as string
string XML_string = reader.ReadToEnd();
string result = XML_string;
//return the XMLString data
return result;
}
必须将我的前端电话的标题更改为:“ application / x-www-form-urlencoded”(默认的Internet媒体类型)。
return Restangular.one('').customPOST({
Name: new_player.name,
Created: new Date(),
Affilation: new_player.human,
auth: new_player.fed
}, 'CreatePlayer', {},
{'Content-Type': 'application/x-www-form-urlencoded'
})
或者,您可以使用有角的$ http服务:
$http({
url: 'http://localhost:31736/BusinessService.svc/CreatePlayer',
method: 'POST',
data: "test",
headers: {"Content-Type": "application/x-www-form-urlencoded"}
});
就是这样!然后,我可以序列化结果字符串并前进到我的业务逻辑。
public string CreatePlayer(System.IO.Stream data) {
//convert stream data to StreamReader
System.IO.StreamReader reader = new System.IO.StreamReader(data);
//read StreamReader data as string
string XML_string = reader.ReadToEnd();
System.Web.Script.Serialization.JavaScriptSerializer json_serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
BusinessObjects.Player Player = json_serializer.Deserialize<BusinessObjects.Player>(XML_string);
return BL_CreatePlayer.CreatePlayer(Player);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句