我有一个对我的 wcf 服务的 ajax POST 调用。当我返回一个字符串(json有效负载)时它工作正常,但是一旦我切换到返回一个'HttpResponseMessage'对象,它就开始给我ERR_CONNECTION_RESET。返回相同的有效负载,但现在我想返回正确的响应,例如 200 和 404。
这是ajax调用:
function Login (cred) {
$.ajax({
type: "POST",
url: ServerConfig.Server + ServerConfig.Service + "/login/",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify(cred),
contentType: "application/json",
dataType: "json",
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
error: loginFailed,
success: loginSuccess
});
}
这是我的 wcf 方法:
public HttpResponseMessage Login(string username, string password)
{
repository = new DbRepository();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);
var res = string.Empty;
var user = repository.Login(username, password);
if (null != user)
{
res = JsonConvert.SerializeObject(user);
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(res)
};
}
else
{
return response;
}
return response;
}
我已经确认通过切换回字符串可以按预期工作。有人可以阐明可能发生的事情吗?
谢谢。
编辑:这是我的“cred”对象的样子以及它是如何创建的:
$('.signin').on("click", function () {
var user = $('.username').val();
var pass = $('.password').val();
var cred = { "username": user, "password": pass };
Login(cred);
});
JSON.stringify(cred) 看起来像这样:
{"username":"Test1234","password":"TestPassword!"}