HttpResponseMessage被响应序列化

时间:2017-05-24 06:53:36

标签: c# ajax asp.net-core

我有一个返回HttpResponseMessage的方法。因此,如果查询正确,则返回BadRequest,否则返回200OK。

我注意到查询总是出现在我的AJAX调用的success方法中。即使我返回了BadRequest。检查我的网络选项卡后,我注意到一些奇怪的行为。一般请求是200OK,但HttpResponseMessage在体内被序列化为JSON。

Response Body

我真的不知道为什么会这样。我的代码如下所示:

[HttpPost]
public async Task<HttpResponseMessage> Register([FromBody] RegisterPresentationModel register)
{
    if (register == null)
        return new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            ReasonPhrase = "Value passed in request is null"
        };

    if (register.Password != register.ConfirmPassword)
        return new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            ReasonPhrase = "Passwords do not match"
        };
    var user = new UserPassPresentationModel
    {
        Email = register.Email,
        UserName = register.UserName,
        Roles = new List<string> {ApplicationRoles.User},
        Password = register.Password,
        ConfirmPassword = register.ConfirmPassword
    };
    return await _userRepo.Add(user);
}

AJAX调用是这样的:

$.ajax({
    url: "/api/auth/",
    type: "post",
    headers: {
        'Content-Type': "application/json"
    },
    data: JSON.stringify(register),
    success: function (data) {
        console.log(data);
    },
    error: function (data) {
        element.registerform.isValid = false;
        element.registerform.error = data.responseText;
    }
});

0 个答案:

没有答案