1
我無法弄清楚我的生活,基本上,我使用Visual Studio來實現客戶端 - 服務器系統。我對此很陌生,所以這可能看起來像一個簡單的問題。錯誤404從Web客戶端發佈數據到Web服務器
我想簡單地允許用戶註冊到系統並將其詳細信息存儲在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;
}
}
}
一個觀察:你的 客戶端代碼使用request.Method =「POST」;你的服務器端有AcceptVerbs(「GET」)屬性,也許? –
是的,當我嘗試將其更改爲POST時,它仍然返回404錯誤:/ –
您是否可以簡化它並調用沒有任何參數的操作? –