Home > Back-end >  How to fetch the value of token in ASP.NET Core MVC
How to fetch the value of token in ASP.NET Core MVC

Time:05-29

I am creating to login page in ASP.NET Core MVC and API. I fetched data

{
    "UserId": 4,
    "userName": "admin",
    "EmailId": "[email protected]",
    "Password": "123",
    "Role": "admin",
    "Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjQiLCJyb2xlIjoiYWRtaW4iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3ZlcnNpb24iOiJWMy4xIiwibmJmIjoxNjUzODA2NTE4LCJleHAiOjE2NTM5NzkzMTgsImlhdCI6MTY1MzgwNjUxOH0.ogp1MHNrKPvX7P2-nqbHJewOlgS0sSUNcKwADhOeIFc",
    "Mobile": null,
    "Address": null,    
    "created_at": "0001-01-01T00:00:00",
    "updated_at": "0001-01-01T00:00:00"
}

string data = response.Content.ReadAsStringAsync().Result;
ViewBag.Status =  data;

It displays all the data. But I need to fetch only Token value from that data - not all values.

How to read only the token? It should be stored in session.

CodePudding user response:

A good way to use JSON in C# is with JSON.NET

An example of how to use it:

public class Response
{
    public Response(string rawResponse)
    {
        var obj = JObject.Parse(rawResponse);
        UserId = int.Parse(obj["UserId"].ToString());

        userName = obj["userName"].ToString();
        //...
        Token = obj["Token"].ToString();
        //...
        
    }
    public int UserId { get; set; }
    public string userName { get; set; }

    public string EmailId { get; set; }

    public String Password { get; set; }

    public string Role { get; set; }

    public string Token { get; set; }

    // other properties

}


// Use
private void Run()
{
  string data = response.Content.ReadAsStringAsync().Result;

  Response response = new Response(data );

  Console.WriteLine("Token: "   response.Token);

 }

CodePudding user response:

Here is my Code. I want store Token Value in Session. I am using API and MVC Asp.net core. I retrieved data full value but i need only Token value

    [HttpPost]
    public ActionResult Index(Login model)
    {           
        HttpResponseMessage response = GlobalVariables.WebApiClient.PostAsJsonAsync("Users", model).Result;

        IEnumerable<Login> error = null;
     
        if (response.IsSuccessStatusCode)
        {
            string data = response.Content.ReadAsStringAsync( ).Result;
                           
           // Session["TokenNumber"] = data;
         
        }
        else 
        {
         
            error = Enumerable.Empty<Login>();

            ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
        }

        return View(model);
    }
  • Related