Angular:http.post请求中的捕获响应错误描述

时间:2018-08-31 08:19:31

标签: c# angular error-handling

我有一个Angular登录方法,该方法从发布请求中接收来自Asp.Net Web Api的令牌,并且如果凭据不正确,我会抛出“ invalid_grant”错误,就像在下一部分C#代码中可以看到的那样:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            SetContextHeaders(context);
            string strDomain = Settings.Default.ADDomain;

            try
            {
                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, strDomain))
                {
                    // validate the credentials
                    bool isValid = pc.ValidateCredentials(context.UserName, context.Password);

                    if (!isValid)
                    {
                        context.SetError("invalid_grant", Culture.GetResxNameByValue("wfrh_auth_incorrectusernamepassword"));
                        return;
                    }
                }
            }
            catch (PrincipalServerDownException ex) {
                context.SetError("adserver_not_reachable", Culture.GetResxNameByValue("wfrh_auth_serverunreachable"));
                LogUtils.logText(Utils.getRunningAssembly(), Utils.getRunningMethod(), ex.InnerException.Message);
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));

            context.Validated(identity);
        }

浏览器将错误显示为400“ Bad Request”,但在“网络”标签中的错误详细信息中,您可以看到:

{error: "invalid_grant", error_description: "Incorrect username or password."}
error
:
"invalid_grant"
error_description
:
"Incorrect username or password."

这是正确的,但是我无法在Angular方法中捕获该错误描述。我收到的只是一个带有“错误请求”文字的字符串。

这是我的登录方法:

let headers = {
    headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    })
}

let tokenParams = "grant_type=password&username=" + username + "&password=" + password;

return this.http.post<any>('http://localhost:9810/token', tokenParams, headers)
    .pipe(
        map(user => {
            // login successful if there's a jwt token in the response
            if (user && user.access_token) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({ user }));
                return user;
            }
            return user;
        }) , catchError((err:JSON) => {
            console.log("" + err);
            return Observable.throw(err);
        }),
    );

事实是我是Angular的新手,我在错误处理方面经验不足。

任何帮助将不胜感激。

更新1:

最奇怪的是,从AngularJS执行http.post如下所示。

$http({
    url: baseUrl + '/token',
    method: "POST",
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    data: 'grant_type=password' + '&username=' + username + '&password=' + password
}).then(function (response) {
    alert(response.data.access_token);
}, function (response) {
    alert(response.data.error_description);
});

0 个答案:

没有答案