使用HttpResponseMessage 401在Ajax帖子上始终成功 [英] Always success on ajax post with HttpResponseMessage 401

查看:273
本文介绍了使用HttpResponseMessage 401在Ajax帖子上始终成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是在客户端的ajax帖子上得到statusCode=200,而服务器用HttpStatusCode.Unauthorized回答.

I always get statusCode=200 on ajax post at client side, while servers answers with HttpStatusCode.Unauthorized.

我的控制器代码:

public class AccountApiController : ApiController
{
    public HttpResponseMessage Login(HttpRequestMessage request, [FromBody]LoginViewModel loginModel)
    {
        return request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized login.");
    }
}

我的Ajax代码:

$.ajax({
    url: '/api/accountapi/login',
    type: 'POST',
    data: data
    })
    .done(function (object, status, xhr) {
        alert("Success: " + xhr.status + " : " + xhr.statusText);
    })
    .always(function (object) {
        $("#output").text(JSON.stringify(object, null, 4));
    });

结果:带有文本Success: 200 : OK的警报 和带有以下内容的输出窗口:

Result: alert with text Success: 200 : OK and output window with:

{
    "Message": "Unauthorized login."
}

因此,我可以获得文本错误消息,但是我需要获取HttpStatusCode来处理错误语句.请帮帮我.

So, I can get text error message, but i need to get HttpStatusCode to handle error statements. Help me, please.

有关此问题的更多信息以及Brock Allen提供的优雅解决方案: http: //brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/

More information about this issue and elegant solution from Brock Allen: http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/

推荐答案

可能是您返回HttpStatusCode.Unauthorized后,表单认证模块将您的页面重定向到登录页面.

It might be that your page is redirecting to a login page by the forms authentication module as soon as you return HttpStatusCode.Unauthorized.

从MSDN:

所有未经身份验证的用户都被拒绝访问您的任何页面 应用.如果未经身份验证的用户尝试访问页面,则 表单身份验证模块将用户重定向到登录页面 由forms元素的loginUrl属性指定.

All unauthenticated users are denied access to any page in your application. If an unauthenticated user tries to access a page, the forms authentication module redirects the user to the logon page specified by the loginUrl attribute of the forms element.

然后以状态代码200进入登录页面或将其重定向到的任何页面.

The login page, or whatever page it's being redirected to, is then served with status code 200.

这篇关于使用HttpResponseMessage 401在Ajax帖子上始终成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆