我无法想象我的生活,基本上,我使用Visual Studio来实现客户端 - 服务器系统。我是新手,所以这似乎是一个简单的问题。
我想简单地允许用户注册到系统并将他们的详细信息存储在SQL服务器上。我有一个Web客户端,它有一个与Web服务器通信的通信类,在这个通信类上我试图发布用户输入的详细信息并将它们路由到服务器端的必要类,这将处理插入记录。
我知道代码是正确的我只是非常确定存在一些语法错误或其他问题。基本上我没有找到404错误。我已经检查了几个小时,我的url地址在客户端和服务器端完全相同。任何帮助将不胜感激,这对我来说是一场噩梦。
类'UserM'也只是包含用户表信息的模型。我还重新检查了端口,它们是正确的。
客户端通信类:
private static string URL = "http://localhost:12804/api/Users/";
public static UserM Register(UserM user)
{
var request = HttpWebRequest.Create(String.Format(URL + "Register?email={0}&password={1},forename={2},surname={3},dob={4},balance={5},nooflogins={6},joindate={7}", user.Email, user.Password, user.Forename, user.Surname, user.DoB, user.Balance, user.NoOfLogins, user.JoinDate));// "/save" or "/update"
request.ContentType = "application/json"; // tell the API we want Json returned
request.Method = "POST";
try
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string JSONPost = JsonConvert.SerializeObject(user, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
streamWriter.Write(JSONPost);
streamWriter.Flush();
streamWriter.Close();
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
return null;
}
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return JsonConvert.DeserializeObject<UserM>(reader.ReadToEnd()); //if user is succesfully inserted into database
}
}
}
catch (Exception ex)
{
return null;
}
}
服务器端类:
[Route("api/Users/Register"), AcceptVerbs("GET")]
public UserM RegisterUser(string email, string password, string forename, string surname, DateTime DoB, decimal balance, int NoOfLogins, DateTime joindate)
{
using (TestDBDataContext tdb = new TestDBDataContext())
{
//check is user already exists in database
if (tdb.User.Where(x => x.Email == email).Count() <= 0)
{
User temp = new User()
{
Email = email,
Password = password,
Forename = forename,
Surname = surname,
DoB = DoB,
Balance = balance,
NoOfLogins = NoOfLogins,
JoinDate = joindate
};
tdb.User.InsertOnSubmit(temp);
try
{
tdb.SubmitChanges();
return new UserM(temp);
}
catch (Exception ex)
{
return null;
}
}
else
{
return null;
}
}
}