【发布时间】:2019-01-27 05:11:35
【问题描述】:
我在我的 Angular 应用程序中使用 .NET Core 2.1 API
下面是我的 API
[HttpPost("[action]")]
public ObjectResult CheckLogIn([FromBody] LogIn model)
{
try
{
UserInfo user = new UserInfo();
using (IDbConnection db = new SqlConnection(configuration.GetConnectionString("constr")))
{
user = db.Query<UserInfo>("SP_Loginportal",
new
{
UserId = model.EmployeeCode,
Password = util.EncryptMD5(model.Password)
}, commandType: CommandType.StoredProcedure).FirstOrDefault();
}
if (user != null)
{
return StatusCode(200, user);
}
else
{
return StatusCode(401, new ResultSet() { Message = "Invalid Credential or Unauthorized", StatusCode = 401 });
}
}
catch (SqlException sx)
{
return StatusCode(503, new ResultSet() { Message = "Service is Currently Unavailable", StatusCode = 503 });
}
catch (Exception ex)
{
return StatusCode(500, new ResultSet() { Message = ex.Message, StatusCode = 500 });
}
finally
{
}
return StatusCode(404, new UserInfo());
}
角度来看
LogIn() {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
var payload = JSON.stringify(this.login);
var url = this.baseURL + 'api/LogIn/CheckLogIn/';
this.http.post<UserInfo>(url, payload, httpOptions)
.subscribe(result => {
if (result != null) {
sessionStorage.setItem("UserID", result.StaffCode);
sessionStorage.setItem("UserName", result.StaffName);
sessionStorage.setItem("UserRole", result.StaffRole);
sessionStorage.setItem("BrancName", result.BranchName);
sessionStorage.setItem("BranchCode", result.BranchCode);
this.router.navigate(['/indusindform'])
}
else {
this.ErrorMessage = "Invalid";
}
}, error => console.error(error))
}
在 http.post 调用中,在 subscribe 块中,我想检查 API 状态代码是 200 还是 401 、 503 还是 500 ,而不是基于此我想显示我在 ResultSet 中返回的消息。
如何在使用数据之前检查 API 状态码?
【问题讨论】:
-
@AmitChigadani 如何在 http 调用中使用它?
-
只需打印响应,您将看到所有这些属性。您还应该将
observe: 'response'添加到您的httpOptions参数中,如下面的答案所示。 -
@AmitChigadani ,添加后观察:'响应'它给出错误 - 观察的属性类型不兼容
-
并打印什么响应??必须声明任何变量?
标签: angular http-post angular5 asp.net-core-webapi