Search code examples
c#asp.net-coreasp.net-core-webapi

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.


Solution

  • 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.