3

Is there any way to remove a header from a RestSharp RestRequest?

Ive stumbled upon this issue in the project page, but cannot see it was ever applied:

https://github.com/restsharp/RestSharp/issues/959

There is one suggestion to use request.Parameters.remove(), assuming with the header name as a parameter, but i don't see how that should correspond to removing a header.

I'm likely just confused, can anyone help?

2 Answers 2

3

The Parameters property of RestRequest is poorly-named. It should be called Headers because that's all it is; a List of the request headers. Therefore, to remove one or more headers from the request, you must first find the header in the list and then remove it with the List.Remove() method.

For example, this snippet removes every Authorization header from the request. I used this to remove old and expired auth tokens from a request before adding a new one.

foreach (var oldAuthHeader in request.Parameters.Where(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)).ToArray())
{
    request.Parameters.Remove(oldAuthHeader);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Right. It's a list of kvps with a bad name.
Parameters property isn't just headers. It could also UrlSegment, QueryString, Cookie, etc. Check enum RestSharp.ParameterType.
@YanF. are you speaking of these? restsharp.org/usage/parameters.html
-1

Faster implementation of Nathan's response.

var authParam = requestHeadersAdded.Parameters.Find(p => p.Name == "Authorization");
requestHeadersAdded.Parameters.Remove(authParam);

Instead of wrapping the LINQ .Where in a foreach loop, this only loops one time.

1 Comment

FYI the expression of a foreach loop is only evaluated once and so you can use a LINQ expression and it will only loop once. Also you should avoid using == for string comparison and instead you should explicitly declare the StringComparison to use.

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.