从另一个项目调用时,API 不发送任何数据并显示 HTTP 错误 204



我在ASP.net API中有一个方法,当它使用HTTP Get-method获得请求时,它会发送JWT令牌。在fiddler上,当我调用这个API时,一切都很好;但当我用另一个项目调用同一个API(在angular 8中制作(时,我得到了HTTP 204错误,并且没有数据。在Angular Project中,我在我的组件的NgOnInit上调用了这个API。

这是API 的代码

[HttpGet("[action]")]
public string GetToken()
{
try
{
string key = "FIPL@321456222222222222222222222222222222222222222222222222222222222222222222"; //Secret key which will be used later during validation    
var issuer = "http://localhost:1424/";  //normally this will be your site URL    
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
//Create a List of Claims, Keep claims name short    
var permClaims = new List<Claim>();
permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
//permClaims.Add(new Claim("valid", "1"));
//permClaims.Add(new Claim("userid", "1"));
//permClaims.Add(new Claim("name", "bilal"));
//Create Security Token object by giving required parameters    
var token = new JwtSecurityToken(issuer, //Issure    
issuer,  //Audience    
permClaims,
expires: DateTime.Now.AddDays(1),
signingCredentials: credentials);
var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);
enter image description here
return (String)jwt_token;
}
catch (Exception ex)
{
return (string)ex.Message ;
}
}

这里是调用API的角度代码。

ngOnInit() {
let obj = JSON.parse(localStorage.getItem("Auth"));
this.DepartmentModel._iBPNo = obj.BPNo;
this.DepartmentModel._iLoginNo = obj.LoginNo;
//Here I am Calling the API to get token
this.httpServices.get("http://localhost:52484/api/Token/gettoken/", null, (data) => {
alert(JSON.stringify(data));
localStorage.setItem("Token", JSON.stringify(data));

}, (error) => {
console.log(error);
});

if (JSON.parse(sessionStorage.getItem("PDEP"))) {
this.DeptNo = JSON.parse(sessionStorage.getItem("PDEP"));
this.LoadData();
}
}

这是我的小提琴页响应链接。

您可以尝试直接订阅HTTP请求:

this.httpServices.get("http://localhost:52484/api/Token/gettoken").subscribe((data) => {
alert(JSON.stringify(data));
localStorage.setItem("Token", JSON.stringify(data));
}, (error) => {
console.log(error);
});

最新更新