0

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

{
    "UserId": 4,
    "userName": "admin",
    "EmailId": "admin@gmail.com",
    "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"
}

 [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);
}

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.

Rakural
  • 1
  • 2

3 Answers3

0

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);

 }
Mohsen Saleh
  • 139
  • 1
  • 10
0

It depends on your authentication, are you using JWT? why you are not sending token in header attribute?

if this data you post to Index method, then the token should exist in model.Token,

using the best practice, you need to have login method, that verify the user, then return a token for the user to be used in the header for each request, and by using AuthorizeAttribute you should authorize the user

Joe
  • 2,381
  • 1
  • 17
  • 17
0

If you are using .NET Core and Token Authentication, get it using

var _bearer_token = Request.Headers[HeaderNames.Authorization].ToString()

Original Answer: https://stackoverflow.com/a/61395803/3559462

Vikas Lalwani
  • 1,041
  • 18
  • 29