我正在将Wcf服务用于Angular JS Application。我使用类库项目创建了wcf服务。我把它托管到Service.svc文件中。当我点击提交按钮时,我在文本框中输入了所需信息,显示以下错误。
System.NullReferanceException: Object reference not set an instance of an object.
Angular JS application showing following error ..
POST http://localhost:52098/HalifaxIISService.svc/RegisterUser 400 (Bad Request)
这是界面。
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "/RegisterUser")]
bool RegisterUser(UserLogin UserLogin);
这是接口的实现..
public bool RegisterUser(UserLogin UserLogin)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
// SqlConnection is in System.Data.SqlClient namespace
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spRegisterUser", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter username = new SqlParameter("@Username", UserLogin.Username);
// FormsAuthentication calss is in System.Web.Security namespace
string encryptedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(UserLogin.Password, "SHA1");
SqlParameter password = new SqlParameter("@Password", encryptedPassword);
SqlParameter email = new SqlParameter("@Email", UserLogin.Email);
cmd.Parameters.Add(username);
cmd.Parameters.Add(password);
cmd.Parameters.Add(email);
con.Open();
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
return false;
}
else
{
return true;
}
}
}
这是Script.Js文件代码..
/// <reference path="../angular.min.js" />
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Username = "";
$scope.Password = "";
$scopr.Email = "";
}
$scope.createuser = function () {
var User = {
Username: $scope.Username,
Password: $scope.Password,
Email: $scope.Email
};
if ($scope.OperType === 1) {
var promisePost = myService.post(User);
promisePost.then(function (pl) {
$scope.User_Id = pl.data.User_Id;
window.location.href = "/Login/Index";
ClearModels();
}, function (err) {
$scope.msg = "Password Incorrect !";
console.log("Some error Occured" + err);
});
}
}
}]);
app.service("myService", function ($http) {
//Create new record
this.post = function (User) {
var request = $http({
method: "post",
url: "http://localhost:52098/HalifaxIISService.svc/RegisterUser",
data: User
});
return request;
}
})
我不知道为什么会收到此错误。任何帮助都将受到高度赞赏。
答案 0 :(得分:0)
null引用表示UserLogin对象为null。我先查看以下内容。
确保UserLogin是与数据成员对应的用户名,密码和电子邮件值的数据合同。在post请求中,将用户对象串起来。
data : JSON.stringify(User)
检查以下链接以获取更多信息,我会确保$ http正在设置正确的内容类型。
Javascript Array as WCF Webservice Parameter
编辑:我建议使用与类名称不同的值来命名变量。我不确定c#如何处理它。