2

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.

3
  • Possible duplicate of How to extract custom header value? Commented Dec 8, 2018 at 3:49
  • Thanks for reply...it shows reading data from request but I want to read data from response header Commented Dec 8, 2018 at 4:02
  • Can you add the code of the getRole-method? I think it’s the source of confusion Commented Dec 8, 2018 at 4:12

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Using StringValues:

var headers = response.Headers;
string role = "";
if (headers.TryGetValues("Role", out Microsoft.Extensions.Primitives.StringValues headerValues))
{
    role = headerValues.FirstOrDefault();
}

1 Comment

I don't know why in my code there is no headers.TryGetValues but headers.TryGetValue with no 's'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.