【发布时间】:2016-03-25 20:16:56
【问题描述】:
我正在使用 MVC 模型创建登录表单。实际上,我的应用程序可以正确地 GET、DELETE 甚至 POST(创建)。当我尝试在登录方法中使用 POST 方法发送 JSON 对象时,会引发“错误请求”异常。
这里有一些代码可以解决我的问题: 在LoginController类中,我实现了登录方法如下:
[HttpPost]
public ActionResult Login(LoginViewModel lvm)
{
LoginServiceClient lsc = new LoginServiceClient();
bool userFound_flag = lsc.Login(lvm.User);
if (userFound_flag)
return RedirectToAction("Index_User", lvm.User);
else
return RedirectToAction("Create");
}
}
在模型文件夹中,这个类 LoginServiceClient 是我实现登录方法的地方,该方法将上传 JSON 对象,如下所示:
public bool Login(User user)
{
try
{
var webClient = new WebClient();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, user);
string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
String str = webClient.UploadString(BASE_URL + "login", "POST", data);
return true;
}
catch (WebException webEx)
{
return false;
}
}
如您所见,String str = webClient.UploadString(BASE_URL + "login", "POST", data); 行是引发异常的地方。此函数与我用来在数据库中创建新对象的 Create 函数相同。字符串数据例如"\"City\":null,\"Country\":null,\"Email\":null,\"FirstName\":null,\"Gender\":null,\"Id\":0,\"LastName\":null,\"Password\":\"EEPass\",\"Telephone\":0,\"UserName\":\"EE\"}"
在我的服务器端,这里是登录方法。以下方法在 IloginService.cs 类中:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "login", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
User Login(User _user);
在 LoginServe.svs.cs 类中,我连接到我的数据库:
public User Login(User _user)
{
using (OnlineStoreDBEntities ose = new OnlineStoreDBEntities())
{
return ose.UserEntities.Where(pe => pe.Username == _user.UserName && pe.Password == _user.Password).Select(pe => new User
{
Id = pe.Id,
Email = pe.Email,
FirstName = pe.FirstName,
LastName = pe.LastName,
//Telephone = Convert.ToInt32(pe.Telephone),
Country = pe.Country,
City = pe.City,
//Gender = Convert.ToInt32(pe.Gender)
}).First();
};
}
最后,为了确保我清楚,Create 和 Login 函数在 Model 类中具有相同的主体。我也在使用 POST 方法,因为应该隐藏一些数据,例如密码。但上传字符串无法上传数据(JSON 字符串)。当我显示数据字符串时,它包含我需要的数据,所以它不是空的。
【问题讨论】:
标签: c# json http-post wcf-rest