我在Angular APP中使用.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状态代码之前检查其状态?
答案 0 :(得分:2)
在httpOptions中使用此:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
observe: 'response' // add this line
};