简体   繁体   中英

Set Accept header on ServiceStack JsonServiceClient

I am using the ServiceStack.JsonServiceClient to attempt to make a URL request with a custom value for the Accept header, but am unable to find a way to make the call.

The service call is to retrieve the topics for a repository through the GitHub API. This is currently a preview feature, and requires additional information to be sent on the accept header as a custom media type. ( https://developer.github.com/v3/repos )

I'm using Service Stack and making a C# .NET call to the API endpoint, and I'm struggling to find the appropriate way to update the accept header on the request. I've tried two strageies.

  1. Create an HttpWebRequest with the header and pass it to the client

      Uri uri = new Uri(requestUrl, UriKind.Absolute); HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(uri); webRequest.Accept = "application/vnd.github.mercy-preview+json"; HttpWebResponse webResponse = client.Get<HttpWebResponse>(webRequest); 

    The requestUrl is a string of the form https://api.github.com/repos/{owner}/{repo}?access_token={token} . It successfully creates both the Uri and the HttpWebRequest objects but then throws an exception on the client.Get , claiming Invalid URI: The format of the URI could not be determined.

    Calling the API with the string URL: HttpWebResponse webResponse = client.Get<HttpWebResponse>(requestUrl); succeeds without issue (but the custom header value is not passed).

  2. Set the header on the client itself. client.AddHeaders throws an exception because Accept is a restricted header. I have been unable to find any other way to set the header directly on the client (although this would probably be the nicest solution).

Thank you, and let me know if there is anything else that I can provide.

You can use the RequestFilter to modify the HttpWebRequest before requests are sent, eg:

var client = new JsonServiceClient(baseUrl) {
    RequestFilter = req => req.Accept = acceptHeader
};

Note: ServiceStack's C#/.NET Service Clients should only be used for calling ServiceStack Services. For calling 3rd Party APIs you should instead use HTTP Utils , eg:

var body = url.GetStringFromUrl(requestFilter: req => {
    req.Accept = acceptHeader;
});

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