不允许发布方法

时间:2015-08-31 10:54:11

标签: c# angularjs wcf restangular

我尝试了这个例子:http://www.c-sharpcorner.com/UploadFile/surya_bg2000/developing-wcf-restful-services-with-get-and-post-methods/

GET方法完美,但不是POST方法。调试时,strReturnValue变量始终为空。当我继续时,状态为:405 Method Not Allowed。我做错了什么?

在C#中,我必须将方法从POST更改为OPTIONS。

我正在使用Restangular(角度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");               
        });

enter image description here

修改

[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;
    }

1 个答案:

答案 0 :(得分:0)

必须将我前端的标题更改为:'application / x-www-form-urlencoded'(默认的互联网媒体类型)。

        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'
        })

或者你可以使用angular $ 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);
    }