Click here to Skip to main content
15,894,198 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to pass value from action to action on web api  asp.net core 2.2 ?

i return data from action and i need to user this data returned on another action so that what i make to do that please ?
i need to get access token string value returned from action and reuse it inside
another action to convert it to json file ?
How to do that please ?

What I have tried:

C#
[HttpPost(Contracts.ApiRoutes.Login.UserLogin)]
        public  IActionResult PostUserLogins([FromBody]Users user)
        {
             user.Branches = branchesList;
                user.LoginTime = DateTime.Now.ToString();
                user.AccessToken = ?????? how to get it from access token action;
                JsonResults = JsonConvert.SerializeObject(user);
        }



C#
[AllowAnonymous]
[HttpGet("GetToken")]
public IActionResult GetToken(string user, string password)
{
var jwt = new JwtToken();
//Secret ID of the User from Database
var sid = GetFromDB(user,password);

List<Claim> claimslist = new List<Claim>()
{
new Claim(ClaimTypes.Sid, sid ),
new Claim(ClaimTypes.Role, role),
new Claim(ClaimTypes.Role, "Doctor")
};

var retval = new JwtSecurityToken(
issuer: "https://www.mysupervwebsite.com",
audience: "https://www.mysupervwebsite.com",
claims: claimlist, 
expires: DateTime.UtcNow.AddSeconds(120),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.Utf8.GetBytes("MySuperSecretPassword")), SecurityAlgorithms.HmacSha256)

);

string token = new JwtSecurityTokenHandler().WriteToken(retval);


return Ok(token);

}
Posted
Updated 6-Sep-19 8:26am
Comments
ahmed_sa 2-Sep-19 8:04am    
can any one help me

1 solution

Two options:

1) Call the existing method, cast the result to OkObjectResult, and cast the Value property to a string:
C#
IActionResult tokenResult = GetToken(username, password);
OkObjectResult okResult = (OkObjectResult)tokenResult;
user.AccessToken = (string)okResult.Value;
OkObjectResult(Object) Class (Microsoft.AspNetCore.Mvc) | Microsoft Docs[^]

2) Refactor the GetToken action to call another method which returns the token string, and call that method:
C#
private string GetTokenCore(string user, string password)
{
    var jwt = new JwtToken();
    ...
    string token = new JwtSecurityTokenHandler().WriteToken(retval);
    return token;
}

[AllowAnonymous]
[HttpGet("GetToken")]
public IActionResult GetToken(string user, string password)
{
    return Ok(GetTokenCore(user, password));
}

[HttpPost(Contracts.ApiRoutes.Login.UserLogin)]
public  IActionResult PostUserLogins([FromBody]Users user)
{
    ...
    user.AccessToken = GetTokenCore(username, password);
    ...
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900