将json数据从angularjs传递到WCF是抛出400错误请求错误

本文关键字:错误 请求 WCF 数据 json angularjs | 更新日期: 2023-09-27 17:59:29

点击按钮调用此函数角度函数

$scope.CreateNewTopic = function () {
          var userdata = {
        TopicName:$scope.topicname,
        TopicDescription: $scope.topicdescription,
        OriginalPosterID: $scope.userid,
        CategoryID: $scope.selectedcategory
    };
        DataService.InsertTopicObject(userdata) 

服务方法如下

InsertTopicObject: function (topic) {
            $http({
                method: 'POST',
                url: connectionurl + 'InsertNewTopic',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' },
                data:  topic 
            })
            .success(function (data, status, headers, config) {
                // successcallback(data); 
                console.log(data);
            })
            .error(function (data, status, headers, config) {
                $log.warn(data, status, headers, config);
            })
        }

WCF-

[OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/InsertNewTopic", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped)]
        int InsertNewTopic(InsertNewTopic InsertTopicObject);
public int InsertNewTopic(InsertNewTopic InsertTopicObject) {
            return SqlHelper.ExecuteNonQuery(SqlConnectionString.GetConnection(), CommandType.StoredProcedure, Constants.SP_Name.ToString(), new SqlParameter("TopicName", InsertTopicObject.TopicName), new SqlParameter("TopicDescription", InsertTopicObject.TopicDescription), new SqlParameter("OriginalPosterID", InsertTopicObject.OriginalPosterID), new SqlParameter("CategoryID", InsertTopicObject.CategoryID));
        }

我得到以下错误。

在此处输入图像描述

将json数据从angularjs传递到WCF是抛出400错误请求错误

您应该仔细检查发送的数据。指定RequestFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped时,预期的正文格式为:{"parameterName":parameterValue}。所以你有两个选择:

1-您可以将BodyStyle更改为WebMessageBodyStyle.Bare
2-另一种选择是"打包"发送数据:

$http({
    method: 'POST',
    url: connectionurl + 'InsertNewTopic',
    data:  {
        'InsertTopicObject' : topic
    }
})