简体   繁体   中英

Using RestSharp to get header value from HttpResponseMessage in web API?

I'm having some trouble getting a token from a HttpResponseMessage using RestSharp. Here is my API controller code:

public HttpResponseMessage Create(long id)
{
    var token = _tokenCreator.CreateToken(id);
    var response = new HttpResponseMessage();
    response.Headers.Add("Token", token);
    response.StatusCode = HttpStatusCode.OK;

    return response;
}

This is generating the token like I want, and creating the response pictured below. When I call the method with Postman, this is the body of the response that I receive. This is the same result I get if I look at the Content property of the response in my code that sends the request.

Picture of response body.

There is clearly a header section there, but it's not being recognized by RestSharp in my calling code.

public string CreateToken(long id)
{
    var client = new RestClient(apiUrl);
    var request = new RestRequest(Method.GET)
    {
        Resource = "tokencreator/create"
    }
    request.AddQueryParameter("id", id.ToString());

    var response = client.Execute(request);
    var headers = response.Headers.ToList();

    // Here is what I want to do, but does not return a result
    var tokenHeader = headers.Find(x => x.Name == "Token");
    if(tokenHeader != null)
    {
        return tokenHeader.Value.ToString();
    }

    return "no token";
}

If I loop through and print the response's headers, these are the results:

  • Transfer-Encoding chunked
  • X-SourceFiles =?UTF-8?B?QzpccHJvamVjdHNcYXBpXEVudGl0bGVtZW50QWNjZXNzXHRva2VuY3JlYXRvclxjcmVhdGU=?=
  • Content-Type application/json; charset=utf-8
  • Date Mon, 03 Apr 2017 16:00:18 GMT
  • Server Kestrel
  • X-Powered-By ASP.NET

The "Token" header I added in the controller to the response is not there. Is there a simple way to access the "header" section that is appearing in the body of the response?

Edit: Attaching a picture of the "Headers" section of the response from Postman. There is no "Token" header. Any idea why the response.Headers.Add("Token", token) method does not add the header, or am I misunderstanding headers completely?

Picture of headers in Postman response.

So I should have specified that this was a .NET Core application. To fix the problem, I had to go to the Startup.cs file and add the following to the ConfigureServices method:

Change services.AddMvc(); to services.AddMvc().AddWebApiConventions();

You will need the NuGet package Microsoft.AspNetCore.Mvc.WebApiCompatShim, which allows compatibility with the old Web Api 2 way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM