Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read header data from a web API response in .NET Core?

I am calling the web API methods from my client project and returning the value from response header to client:

[HttpPost]
[AllowAnonymous]
[Route("login")]
public IActionResult Login(Users user)
{
    string s = _repository.Users.ValidateUser(user);
    if (s == "success")
    {
        Users u = _repository.Users.FindByUserName(user.UserName);
        int pid = u.PersonId;
        string role = "";
        if (u != null)
        {

            role = _repository.RoleManager.GetRole(u.Id);
        }
        Response.Headers.Add("Role", role);
        return Ok(pid.ToString());
    }

}

And I tried the code below for getting header value in the client application:

[HttpPost]
public IActionResult Login(Users user)
{    
    string pid = "";
    HttpClient client = service.GetService();
    HttpResponseMessage response = client.PostAsJsonAsync("api/mymethod", user).Result;
    Task<string> tokenResult = response.Content.ReadAsAsync<string>();
    pid = tokenResult.Result.ToString();
       
    var headers = response.Headers;
    string role = "";
    if (headers.TryGetValues("Role", out IEnumerable<string> headerValues))
        {
            role = headerValues.ToString();
        }

    return RedirectToAction("Profile");
}

But it returns System.String[] .

Please show me the right way for fetching data from the response header.

like image 757
Tejas Avatar asked Dec 18 '25 08:12

Tejas


1 Answers

I found the solution:

var headers = response.Headers;
string role = "";
if (headers.TryGetValues("Role", out IEnumerable<string> headerValues))
{
    role = headerValues.FirstOrDefault();
}

Don't forget to add a reference to System.Linq.

like image 53
Tejas Avatar answered Dec 19 '25 23:12

Tejas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!