collection)
21 | : base(collection) { }
22 |
23 | public override void Add(string name, string value)
24 | {
25 | WebParameter parameter = new WebParameter(name, value);
26 |
27 | base.Add(parameter);
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleData/sojson.txt:
--------------------------------------------------------------------------------
1 | {
2 | "User":{
3 | "Id":1786,
4 | "Reputation":18332,
5 | "CreationDate":1219071163,
6 | "DisplayName":"John Sheehan",
7 | "EmailHash":"lkdsafadfjsadfkjlsdjflkjdsf",
8 | "Age":"28",
9 | "LastAccessDate":1269715453,
10 | "WebsiteUrl":"http://john-sheehan.com/blog",
11 | "Location":"Minnesota",
12 | "AboutMe":"\r\n\r\n\r\n\r\nVisit managedassembly.com - A community for .NET developers.
\r\n\r\nI am the founder of RIM Systems, maker of SnapLeague, a web-based league management system for recreational athletics.
",
13 | "Views":1639,
14 | "UpVotes":1665,
15 | "DownVotes":427
16 | }
17 | }
--------------------------------------------------------------------------------
/RestSharp/Deserializers/IDeserializer.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | namespace RestSharp.Deserializers
20 | {
21 | public interface IDeserializer
22 | {
23 | T Deserialize(IRestResponse response);
24 |
25 | string RootElement { get; set; }
26 |
27 | string Namespace { get; set; }
28 |
29 | string DateFormat { get; set; }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/RestSharp/Serializers/ISerializer.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | namespace RestSharp.Serializers
20 | {
21 | public interface ISerializer
22 | {
23 | string Serialize(object obj);
24 |
25 | string RootElement { get; set; }
26 |
27 | string Namespace { get; set; }
28 |
29 | string DateFormat { get; set; }
30 |
31 | string ContentType { get; set; }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleData/underscore_prefix.txt:
--------------------------------------------------------------------------------
1 | {
2 | "User":{
3 | "_id":1786,
4 | "_displayName":"John Sheehan",
5 | "Reputation":18332,
6 | "CreationDate":1219071163,
7 | "_displayName":"John Sheehan",
8 | "EmailHash":"lkdsafadfjsadfkjlsdjflkjdsf",
9 | "Age":"28",
10 | "LastAccessDate":1269715453,
11 | "WebsiteUrl":"http://john-sheehan.com/blog",
12 | "Location":"Minnesota",
13 | "AboutMe":"\r\n\r\n\r\n\r\nVisit managedassembly.com - A community for .NET developers.
\r\n\r\nI am the founder of RIM Systems, maker of SnapLeague, a web-based league management system for recreational athletics.
",
14 | "Views":1639,
15 | "UpVotes":1665,
16 | "DownVotes":427
17 | }
18 | }
--------------------------------------------------------------------------------
/readme.txt:
--------------------------------------------------------------------------------
1 | *** IMPORTANT CHANGE IN RESTSHARP VERSION 103 ***
2 |
3 | In 103.0, JSON.NET was removed as a dependency.
4 |
5 | If this is still installed in your project and no other libraries depend on
6 | it you may remove it from your installed packages.
7 |
8 | There is one breaking change: the default Json*Serializer* is no longer
9 | compatible with Json.NET. To use Json.NET for serialization, copy the code
10 | from https://github.com/restsharp/RestSharp/blob/86b31f9adf049d7fb821de8279154f41a17b36f7/RestSharp/Serializers/JsonSerializer.cs
11 | and register it with your request:
12 |
13 | var request = new RestRequest();
14 | request.JsonSerializer = new Shared.JsonSerializer();
15 |
16 | then you can use it in a client:
17 |
18 | var client = new RestClient();
19 | client.Post(request);
20 |
21 | The default Json*Deserializer* is mostly compatible, but it does not support
22 | all features which Json.NET has (like the ability to support a custom [JsonConverter]
23 | by decorating a certain property with an attribute). If you need these features, you
24 | must take care of the deserialization yourself to get it working.
25 |
26 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleClasses/EmployeeTracker.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace RestSharp.Tests.SampleClasses
4 | {
5 | public class EmployeeTracker
6 | {
7 | ///
8 | /// Key: Employee name.
9 | /// Value: Messages sent to employee.
10 | ///
11 | public Dictionary> EmployeesMail { get; set; }
12 |
13 | ///
14 | /// Key: Employee name.
15 | /// Value: Hours worked this each week.
16 | ///
17 | public Dictionary>> EmployeesTime { get; set; }
18 |
19 | ///
20 | /// Key: Employee name.
21 | /// Value: Payments made to employee
22 | ///
23 | public Dictionary> EmployeesPay { get; set; }
24 | }
25 |
26 | public class Payment
27 | {
28 | public PaymentType Type { get; set; }
29 |
30 | public int Amount { get; set; }
31 | }
32 |
33 | public enum PaymentType
34 | {
35 | Bonus,
36 | Monthly,
37 | BiWeekly
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/RestSharp/Extensions/ResponseExtensions.cs:
--------------------------------------------------------------------------------
1 | namespace RestSharp.Extensions
2 | {
3 | public static class ResponseExtensions
4 | {
5 | public static IRestResponse ToAsyncResponse(this IRestResponse response)
6 | {
7 | return new RestResponse
8 | {
9 | ContentEncoding = response.ContentEncoding,
10 | ContentLength = response.ContentLength,
11 | ContentType = response.ContentType,
12 | Cookies = response.Cookies,
13 | ErrorException = response.ErrorException,
14 | ErrorMessage = response.ErrorMessage,
15 | Headers = response.Headers,
16 | RawBytes = response.RawBytes,
17 | ResponseStatus = response.ResponseStatus,
18 | ResponseUri = response.ResponseUri,
19 | Server = response.Server,
20 | StatusCode = response.StatusCode,
21 | StatusDescription = response.StatusDescription
22 | };
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleClasses/ListSamples.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace RestSharp.Tests.SampleClasses
4 | {
5 | public class SimpleTypesListSample
6 | {
7 | public List Names { get; set; }
8 |
9 | public List Numbers { get; set; }
10 | }
11 |
12 | public class InlineListSample
13 | {
14 | public int Count { get; set; }
15 |
16 | public List images { get; set; }
17 |
18 | public List Images { get; set; }
19 | }
20 |
21 | public class NestedListSample
22 | {
23 | public List images { get; set; }
24 |
25 | public List Images { get; set; }
26 | }
27 |
28 | public class EmptyListSample
29 | {
30 | public List images { get; set; }
31 |
32 | public List Images { get; set; }
33 | }
34 |
35 | public class Image
36 | {
37 | public string Src { get; set; }
38 |
39 | public string Value { get; set; }
40 | }
41 |
42 | public class image
43 | {
44 | public string Src { get; set; }
45 |
46 | public string Value { get; set; }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Follow these guidelines, in no particular order, to improve your chances of having a pull request merged in.
2 |
3 | ### Before you do anything else
4 |
5 | * Before reporting an issue or creating a pull request, discuss it in the Google Group http://groups.google.com/group/restsharp
6 |
7 | ### Once a contribution is ready to be submitted
8 |
9 | * Make each pull request atomic and exclusive; don't send pull requests for a laundry list of changes.
10 | * Even better, commit in small manageable chunks.
11 | * Spaces, not tabs. Bracket style doesn't matter. Do not reformat code you didn't touch.
12 | * Changes to XmlDeserializer or JsonDeserializer must be accompanied by a unit test covering the change.
13 | * In general, changes should be accompanied by unit tests to show what was broken and how your patch fixes it.
14 | * No regions except for license header
15 | * Code must build for .NET 3.5 Client Profile, Silverlight 4 and Windows Phone 7
16 | * If you didn't write the code you must provide a reference to where you obtained it and preferably the license.
17 | * Use autocrlf=true `git config --global core.autocrlf true` http://help.github.com/dealing-with-lineendings/
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleClasses/Lastfm.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace RestSharp.Tests.SampleClasses.Lastfm
5 | {
6 | public class Event : LastfmBase
7 | {
8 | public string id { get; set; }
9 |
10 | public string title { get; set; }
11 |
12 | public EventArtistList artists { get; set; }
13 |
14 | public Venue venue { get; set; }
15 |
16 | public DateTime startDate { get; set; }
17 |
18 | public string description { get; set; }
19 |
20 | public int attendance { get; set; }
21 |
22 | public int reviews { get; set; }
23 |
24 | public string tag { get; set; }
25 |
26 | public string url { get; set; }
27 |
28 | public string headliner { get; set; }
29 |
30 | public int cancelled { get; set; }
31 | }
32 |
33 | public class EventArtistList : List { }
34 |
35 | public class artist
36 | {
37 | public string Value { get; set; }
38 | }
39 |
40 | public abstract class LastfmBase
41 | {
42 | public string status { get; set; }
43 |
44 | public Error error { get; set; }
45 | }
46 |
47 | public class Error
48 | {
49 | public string Value { get; set; }
50 |
51 | public int code { get; set; }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/RestSharp.Tests/StringExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Globalization;
4 | using System.Linq;
5 | using System.Text;
6 | using RestSharp.Extensions;
7 | using Xunit;
8 |
9 | namespace RestSharp.Tests
10 | {
11 | public class StringExtensionsTests
12 | {
13 | [Fact]
14 | public void UrlEncode_Throws_ArgumentNullException_For_Null_Input()
15 | {
16 | const string nullString = null;
17 | Assert.Throws(
18 | delegate
19 | {
20 | nullString.UrlEncode();
21 | });
22 | }
23 |
24 | [Fact]
25 | public void UrlEncode_Returns_Correct_Length_When_Less_Than_Limit()
26 | {
27 | const int numLessThanLimit = 32766;
28 | string stringWithLimitLength = new string('*', numLessThanLimit);
29 | Assert.True(stringWithLimitLength.UrlEncode().Length == numLessThanLimit);
30 | }
31 |
32 | [Fact]
33 | public void UrlEncode_Returns_Correct_Length_When_More_Than_Limit()
34 | {
35 | const int numGreaterThanLimit = 65000;
36 | string stringWithLimitLength = new string('*', numGreaterThanLimit);
37 | Assert.True(stringWithLimitLength.UrlEncode().Length == numGreaterThanLimit);
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/RestSharp/Validation/Require.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System;
20 |
21 | namespace RestSharp.Validation
22 | {
23 | ///
24 | /// Helper methods for validating required values
25 | ///
26 | public class Require
27 | {
28 | ///
29 | /// Require a parameter to not be null
30 | ///
31 | /// Name of the parameter
32 | /// Value of the parameter
33 | public static void Argument(string argumentName, object argumentValue)
34 | {
35 | if (argumentValue == null)
36 | {
37 | throw new ArgumentException("Argument cannot be null.", argumentName);
38 | }
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/RestSharp.UWP/RestSharp.nuget.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath)
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/RestSharp.UWP/RestSharp.UWP.nuget.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath)
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/RestSharp/Deserializers/DeserializeAsAttribute.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System;
20 |
21 | namespace RestSharp.Deserializers
22 | {
23 | ///
24 | /// Allows control how class and property names and values are deserialized by XmlAttributeDeserializer
25 | ///
26 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false)]
27 | public sealed class DeserializeAsAttribute : Attribute
28 | {
29 | ///
30 | /// The name to use for the serialized element
31 | ///
32 | public string Name { get; set; }
33 |
34 | ///
35 | /// Sets if the property to Deserialize is an Attribute or Element (Default: false)
36 | ///
37 | public bool Attribute { get; set; }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/RestSharp.Build/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("RestSharp.Build")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("RestSharp.Build")]
12 | [assembly: AssemblyCopyright("Copyright © 2013")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("1cf9b3e7-67bb-4dca-9094-5f8c94ef9587")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
36 |
--------------------------------------------------------------------------------
/RestSharp/Serializers/JsonSerializer.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace RestSharp.Serializers
3 | {
4 | ///
5 | /// Default JSON serializer for request bodies
6 | /// Doesn't currently use the SerializeAs attribute, defers to Newtonsoft's attributes
7 | ///
8 | public class JsonSerializer : ISerializer
9 | {
10 | ///
11 | /// Default serializer
12 | ///
13 | public JsonSerializer()
14 | {
15 | this.ContentType = "application/json";
16 | }
17 |
18 | ///
19 | /// Serialize the object as JSON
20 | ///
21 | /// Object to serialize
22 | /// JSON as String
23 | public string Serialize(object obj)
24 | {
25 | return SimpleJson.SerializeObject(obj);
26 | }
27 |
28 | ///
29 | /// Unused for JSON Serialization
30 | ///
31 | public string DateFormat { get; set; }
32 |
33 | ///
34 | /// Unused for JSON Serialization
35 | ///
36 | public string RootElement { get; set; }
37 |
38 | ///
39 | /// Unused for JSON Serialization
40 | ///
41 | public string Namespace { get; set; }
42 |
43 | ///
44 | /// Content type for serialized content
45 | ///
46 | public string ContentType { get; set; }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/RestSharp.Tests/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 |
8 | [assembly: AssemblyTitle("RestSharp.Tests")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("RestSharp.Tests")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 |
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 |
25 | [assembly: Guid("82c9d878-3d67-40fe-ac6b-6842605a04be")]
26 |
27 | // Version information for an assembly consists of the following four values:
28 | //
29 | // Major Version
30 | // Minor Version
31 | // Build Number
32 | // Revision
33 | //
34 | // You can specify all the values or you can default the Build and Revision Numbers
35 | // by using the '*' as shown below:
36 | // [assembly: AssemblyVersion("1.0.*")]
37 |
38 | [assembly: AssemblyVersion("1.0.0.0")]
39 | [assembly: AssemblyFileVersion("1.0.0.0")]
40 |
--------------------------------------------------------------------------------
/RestSharp/Authenticators/OAuth/OAuthWebQueryInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace RestSharp.Authenticators.OAuth
5 | {
6 | #if !SILVERLIGHT && !WINDOWS_PHONE && !WINDOWS_UWP
7 | [Serializable]
8 | #endif
9 | #if WINDOWS_UWP
10 | [DataContract]
11 | #endif
12 | public class OAuthWebQueryInfo
13 | {
14 | public virtual string ConsumerKey { get; set; }
15 |
16 | public virtual string Token { get; set; }
17 |
18 | public virtual string Nonce { get; set; }
19 |
20 | public virtual string Timestamp { get; set; }
21 |
22 | public virtual string SignatureMethod { get; set; }
23 |
24 | public virtual string Signature { get; set; }
25 |
26 | public virtual string Version { get; set; }
27 |
28 | public virtual string Callback { get; set; }
29 |
30 | public virtual string Verifier { get; set; }
31 |
32 | public virtual string ClientMode { get; set; }
33 |
34 | public virtual string ClientUsername { get; set; }
35 |
36 | public virtual string ClientPassword { get; set; }
37 |
38 | public virtual string UserAgent { get; set; }
39 |
40 | public virtual string WebMethod { get; set; }
41 |
42 | public virtual OAuthParameterHandling ParameterHandling { get; set; }
43 |
44 | public virtual OAuthSignatureTreatment SignatureTreatment { get; set; }
45 |
46 | internal virtual string ConsumerSecret { get; set; }
47 |
48 | internal virtual string TokenSecret { get; set; }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/RestSharp/Extensions/XmlExtensions.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System.Xml.Linq;
20 |
21 | namespace RestSharp.Extensions
22 | {
23 | ///
24 | /// XML Extension Methods
25 | ///
26 | public static class XmlExtensions
27 | {
28 | ///
29 | /// Returns the name of an element with the namespace if specified
30 | ///
31 | /// Element name
32 | /// XML Namespace
33 | ///
34 | public static XName AsNamespaced(this string name, string @namespace)
35 | {
36 | XName xName = name;
37 |
38 | if (@namespace.HasValue())
39 | {
40 | xName = XName.Get(name, @namespace);
41 | }
42 |
43 | return xName;
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/RestSharp.IntegrationTests/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 |
8 | [assembly: AssemblyTitle("RestSharp.IntegrationTests")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("RestSharp.IntegrationTests")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 |
21 | [assembly: ComVisible(false)]
22 |
23 | // The following GUID is for the ID of the typelib if this project is exposed to COM
24 |
25 | [assembly: Guid("d1867cb5-67ee-49c2-afd5-3c9f371b9b4c")]
26 |
27 | // Version information for an assembly consists of the following four values:
28 | //
29 | // Major Version
30 | // Minor Version
31 | // Build Number
32 | // Revision
33 | //
34 | // You can specify all the values or you can default the Build and Revision Numbers
35 | // by using the '*' as shown below:
36 | // [assembly: AssemblyVersion("1.0.*")]
37 |
38 | [assembly: AssemblyVersion("1.0.0.0")]
39 | [assembly: AssemblyFileVersion("1.0.0.0")]
40 |
--------------------------------------------------------------------------------
/RestSharp/Extensions/MonoHttp/Helpers.cs:
--------------------------------------------------------------------------------
1 | //
2 | // System.Web.Util.Helpers
3 | //
4 | // Authors:
5 | // Marek Habersack (mhabersack@novell.com)
6 | //
7 | // (C) 2009 Novell, Inc (http://novell.com)
8 |
9 | //
10 | // Permission is hereby granted, free of charge, to any person obtaining
11 | // a copy of this software and associated documentation files (the
12 | // "Software"), to deal in the Software without restriction, including
13 | // without limitation the rights to use, copy, modify, merge, publish,
14 | // distribute, sublicense, and/or sell copies of the Software, and to
15 | // permit persons to whom the Software is furnished to do so, subject to
16 | // the following conditions:
17 | //
18 | // The above copyright notice and this permission notice shall be
19 | // included in all copies or substantial portions of the Software.
20 | //
21 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 | //
29 |
30 | using System.Globalization;
31 |
32 | namespace RestSharp.Extensions.MonoHttp
33 | {
34 | internal class Helpers
35 | {
36 | public static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/RestSharp.Tests/InterfaceImplementationTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Reflection;
5 | using NUnit.Framework;
6 |
7 | namespace RestSharp.Tests
8 | {
9 | [TestFixture]
10 | public class InterfaceImplementationTests
11 | {
12 | [Test]
13 | public void IRestSharp_Has_All_RestSharp_Signatures()
14 | {
15 | // Arrange
16 | Type restClientImplementationType = typeof(RestClient);
17 | Type restClientInterfaceType = typeof(IRestClient);
18 | const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
19 |
20 | // Act
21 | List compareResult = CompareTypes(restClientImplementationType, restClientInterfaceType,
22 | bindingFlags).ToList();
23 |
24 | compareResult.ForEach(x => Console.WriteLine("Method {0} exists in {1} but not in {2}", x,
25 | restClientImplementationType.FullName, restClientInterfaceType.FullName));
26 |
27 | // Assert
28 | Assert.AreEqual(0, compareResult.Count());
29 | }
30 |
31 | private static IEnumerable CompareTypes(IReflect type1, IReflect type2, BindingFlags bindingFlags)
32 | {
33 | MethodInfo[] typeTMethodInfo = type1.GetMethods(bindingFlags);
34 | MethodInfo[] typeXMethodInfo = type2.GetMethods(bindingFlags);
35 |
36 | return typeTMethodInfo.Select(x => x.Name)
37 | .Except(typeXMethodInfo.Select(x => x.Name));
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleClasses/EnumTest.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace RestSharp.Tests.SampleClasses
3 | {
4 | public enum ByteEnum : byte
5 | {
6 | EnumMin = 0,
7 | EnumMax = 255
8 | }
9 |
10 | public enum SByteEnum : sbyte
11 | {
12 | EnumMin = -128,
13 | EnumMax = 127
14 | }
15 |
16 | public enum ShortEnum : short
17 | {
18 | EnumMin = -32768,
19 | EnumMax = 32767
20 | }
21 |
22 | public enum UShortEnum : ushort
23 | {
24 | EnumMin = 0,
25 | EnumMax = 65535
26 | }
27 |
28 | public enum IntEnum
29 | {
30 | EnumMin = -2147483648,
31 | EnumMax = 2147483647
32 | }
33 |
34 | public enum UIntEnum : uint
35 | {
36 | EnumMin = 0,
37 | EnumMax = 4294967295
38 | }
39 |
40 | public enum LongEnum : long
41 | {
42 | EnumMin = -9223372036854775808,
43 | EnumMax = 9223372036854775807
44 | }
45 |
46 | public enum ULongEnum : ulong
47 | {
48 | EnumMin = 0,
49 | EnumMax = 18446744073709551615
50 | }
51 |
52 | public class JsonEnumTypesTestStructure
53 | {
54 | public ByteEnum ByteEnumType { get; set; }
55 |
56 | public SByteEnum SByteEnumType { get; set; }
57 |
58 | public ShortEnum ShortEnumType { get; set; }
59 |
60 | public UShortEnum UShortEnumType { get; set; }
61 |
62 | public IntEnum IntEnumType { get; set; }
63 |
64 | public UIntEnum UIntEnumType { get; set; }
65 |
66 | public LongEnum LongEnumType { get; set; }
67 |
68 | public ULongEnum ULongEnumType { get; set; }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/RestSharp/Authenticators/SimpleAuthenticator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | namespace RestSharp.Authenticators
20 | {
21 | public class SimpleAuthenticator : IAuthenticator
22 | {
23 | private readonly string usernameKey;
24 |
25 | private readonly string username;
26 |
27 | private readonly string passwordKey;
28 |
29 | private readonly string password;
30 |
31 | public SimpleAuthenticator(string usernameKey, string username, string passwordKey, string password)
32 | {
33 | this.usernameKey = usernameKey;
34 | this.username = username;
35 | this.passwordKey = passwordKey;
36 | this.password = password;
37 | }
38 |
39 | public void Authenticate(IRestClient client, IRestRequest request)
40 | {
41 | request.AddParameter(this.usernameKey, this.username);
42 | request.AddParameter(this.passwordKey, this.password);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/RestSharp.UWP/Properties/RestSharp.UWP.rd.xml:
--------------------------------------------------------------------------------
1 |
2 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/RestSharp/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 |
9 | [assembly: AssemblyTitle("RestSharp")]
10 |
11 | // Setting ComVisible to false makes the types in this assembly not visible
12 | // to COM components. If you need to access a type in this assembly from
13 | // COM, set the ComVisible attribute to true on that type.
14 |
15 | [assembly: ComVisible(false)]
16 |
17 | // The following GUID is for the ID of the typelib if this project is exposed to COM
18 |
19 | [assembly: Guid("d2b12a34-b748-47f9-8ad6-f84da992c64b")]
20 |
21 | #if SIGNED
22 | [assembly: InternalsVisibleTo("RestSharp.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fda57af14a288d46e3efea89617037585c4de57159cd536ca6dff792ea1d6addc665f2fccb4285413d9d44db5a1be87cb82686db200d16325ed9c42c89cd4824d8cc447f7cee2ac000924c3bceeb1b7fcb5cc1a3901785964d48ce14172001084134f4dcd9973c3776713b595443b1064bb53e2eeb924969244d354e46495e9d"),
23 | InternalsVisibleTo("RestSharp.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fda57af14a288d46e3efea89617037585c4de57159cd536ca6dff792ea1d6addc665f2fccb4285413d9d44db5a1be87cb82686db200d16325ed9c42c89cd4824d8cc447f7cee2ac000924c3bceeb1b7fcb5cc1a3901785964d48ce14172001084134f4dcd9973c3776713b595443b1064bb53e2eeb924969244d354e46495e9d")]
24 | #else
25 | [assembly: InternalsVisibleTo("RestSharp.IntegrationTests"),
26 | InternalsVisibleTo("RestSharp.Tests")]
27 | #endif
28 |
--------------------------------------------------------------------------------
/RestSharp/Deserializers/DotNetXmlDeserializer.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System.IO;
20 | using System.Text;
21 | using System.Xml.Serialization;
22 |
23 | namespace RestSharp.Deserializers
24 | {
25 | ///
26 | /// Wrapper for System.Xml.Serialization.XmlSerializer.
27 | ///
28 | public class DotNetXmlDeserializer : IDeserializer
29 | {
30 | public string DateFormat { get; set; }
31 |
32 | public string Namespace { get; set; }
33 |
34 | public string RootElement { get; set; }
35 |
36 | public T Deserialize(IRestResponse response)
37 | {
38 | if (string.IsNullOrEmpty(response.Content))
39 | {
40 | return default(T);
41 | }
42 |
43 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(response.Content)))
44 | {
45 | XmlSerializer serializer = new XmlSerializer(typeof(T));
46 |
47 | return (T) serializer.Deserialize(stream);
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/RestSharp/SharedAssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using RestSharp;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 |
9 | [assembly: AssemblyDescription("Simple REST and HTTP API Client")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("John Sheehan, RestSharp Community")]
12 | [assembly: AssemblyProduct("RestSharp")]
13 | [assembly: AssemblyCopyright("Copyright © RestSharp Project 2009-2014")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 | [assembly: CLSCompliant(true)]
17 | // Version information for an assembly consists of the following four values:
18 | //
19 | // Major Version
20 | // Minor Version
21 | // Build Number
22 | // Revision
23 | //
24 | // You can specify all the values or you can default the Build and Revision Numbers
25 | // by using the '*' as shown below:
26 | // [assembly: AssemblyVersion("1.0.*")]
27 |
28 | [assembly: AssemblyVersion(SharedAssemblyInfo.VERSION + ".0")]
29 |
30 | #if SIGNED
31 | [assembly: AssemblyInformationalVersion(SharedAssemblyInfo.FILE_VERSION)]
32 | [assembly: AssemblyFileVersion(SharedAssemblyInfo.FILE_VERSION + ".0")]
33 | #else
34 |
35 | [assembly: AssemblyInformationalVersion(SharedAssemblyInfo.VERSION)]
36 | [assembly: AssemblyFileVersion(SharedAssemblyInfo.VERSION + ".0")]
37 | #endif
38 |
39 | namespace RestSharp
40 | {
41 | internal class SharedAssemblyInfo
42 | {
43 | #if SIGNED
44 | public const string VERSION = "100.0.0";
45 | public const string FILE_VERSION = "105.2.3";
46 | #else
47 | public const string VERSION = "105.2.3";
48 | #endif
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/RestSharp/Parameter.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | namespace RestSharp
20 | {
21 | ///
22 | /// Parameter container for REST requests
23 | ///
24 | public class Parameter
25 | {
26 | ///
27 | /// Name of the parameter
28 | ///
29 | public string Name { get; set; }
30 |
31 | ///
32 | /// Value of the parameter
33 | ///
34 | public object Value { get; set; }
35 |
36 | ///
37 | /// Type of the parameter
38 | ///
39 | public ParameterType Type { get; set; }
40 |
41 | ///
42 | /// MIME content type of the parameter
43 | ///
44 | public string ContentType { get; set; }
45 |
46 | ///
47 | /// Return a human-readable representation of this parameter
48 | ///
49 | /// String
50 | public override string ToString()
51 | {
52 | return string.Format("{0}={1}", this.Name, this.Value);
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/RestSharp/Deserializers/XmlAttributeDeserializer.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System.Reflection;
20 | using System.Xml.Linq;
21 | using RestSharp.Extensions;
22 |
23 | namespace RestSharp.Deserializers
24 | {
25 | public class XmlAttributeDeserializer : XmlDeserializer
26 | {
27 | protected override object GetValueFromXml(XElement root, XName name, PropertyInfo prop)
28 | {
29 | bool isAttribute = false;
30 |
31 | //Check for the DeserializeAs attribute on the property
32 | DeserializeAsAttribute options = prop.GetAttribute();
33 |
34 | if (options != null)
35 | {
36 | name = options.Name ?? name;
37 | isAttribute = options.Attribute;
38 | }
39 |
40 | if (isAttribute)
41 | {
42 | XAttribute attributeVal = GetAttributeByName(root, name);
43 |
44 | if (attributeVal != null)
45 | {
46 | return attributeVal.Value;
47 | }
48 | }
49 |
50 | return base.GetValueFromXml(root, name, prop);
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleData/GoogleWeather.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleData/4sq.txt:
--------------------------------------------------------------------------------
1 | {
2 | "meta":{
3 | "code":200
4 | },
5 | "response":{
6 | "groups":[
7 | {
8 | "type":"trending",
9 | "name":"Trending Now",
10 | "items":[
11 | {
12 | "id":"4846c5acf964a5206f501fe3",
13 | "name":"Santos Party House",
14 | "contact":{
15 | "twitter":"SantosPartyHaus"
16 | },
17 | "location":{
18 | "address":"96 Lafayette St",
19 | "crossStreet":"btw Walker & White",
20 | "city":"New York",
21 | "distance":1962
22 | },
23 | "categories":[
24 | {
25 | "id":"4bf58dd8d48988d11f941735"
26 | }
27 | ]
28 | }
29 | ]
30 | },
31 | {
32 | "type":"nearby",
33 | "name":"Nearby",
34 | "items":[
35 | {
36 | "id":"42377700f964a52024201fe3",
37 | "name":"Brooklyn Heights Promenade",
38 | "contact":{
39 |
40 | },
41 | "location":{
42 | "address":"Columbia Heights",
43 | "crossStreet":"btw Montague and Middagh",
44 | "city":"Brooklyn",
45 | "distance":342
46 | },
47 | "categories":[
48 | {
49 | "id":"4bf58dd8d48988d163941735",
50 | "name":"Park",
51 | "parents":[
52 | "Great Outdoors"
53 | ],
54 | "primary":true
55 | }
56 | ]
57 | }
58 | ]
59 | }
60 | ]
61 | }
62 | }
--------------------------------------------------------------------------------
/RestSharp/Authenticators/OAuth/HttpPostParameter.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 |
3 | namespace RestSharp.Authenticators.OAuth
4 | {
5 | internal class HttpPostParameter : WebParameter
6 | {
7 | public HttpPostParameter(string name, string value)
8 | : base(name, value) { }
9 |
10 | public virtual HttpPostParameterType Type { get; private set; }
11 |
12 | public virtual string FileName { get; private set; }
13 |
14 | public virtual string FilePath { get; private set; }
15 |
16 | public virtual Stream FileStream { get; set; }
17 |
18 | public virtual string ContentType { get; private set; }
19 |
20 | public static HttpPostParameter CreateFile(string name, string fileName, string filePath, string contentType)
21 | {
22 | HttpPostParameter parameter = new HttpPostParameter(name, string.Empty)
23 | {
24 | Type = HttpPostParameterType.File,
25 | FileName = fileName,
26 | FilePath = filePath,
27 | ContentType = contentType,
28 | };
29 |
30 | return parameter;
31 | }
32 |
33 | public static HttpPostParameter CreateFile(string name, string fileName, Stream fileStream, string contentType)
34 | {
35 | HttpPostParameter parameter = new HttpPostParameter(name, string.Empty)
36 | {
37 | Type = HttpPostParameterType.File,
38 | FileName = fileName,
39 | FileStream = fileStream,
40 | ContentType = contentType,
41 | };
42 |
43 | return parameter;
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleClasses/googleweather.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace RestSharp.Tests.SampleClasses
4 | {
5 | public class xml_api_reply
6 | {
7 | public string version { get; set; }
8 |
9 | public Weather weather { get; set; }
10 | }
11 |
12 | public class Weather : List
13 | {
14 | public string module_id { get; set; }
15 |
16 | public string tab_id { get; set; }
17 |
18 | public string mobile_row { get; set; }
19 |
20 | public string mobile_zipped { get; set; }
21 |
22 | public string row { get; set; }
23 |
24 | public string section { get; set; }
25 |
26 | public Forecast_information forecast_information { get; set; }
27 |
28 | public Current_conditions current_conditions { get; set; }
29 |
30 | //public T forecast_conditions { get; set; }
31 | }
32 |
33 | public class DataElement
34 | {
35 | public string data { get; set; }
36 | }
37 |
38 | public class Forecast_information
39 | {
40 | public DataElement city { get; set; }
41 |
42 | public DataElement postal_code { get; set; }
43 |
44 | public DataElement forecast_date { get; set; }
45 |
46 | public DataElement unit_system { get; set; }
47 | }
48 |
49 | public class Current_conditions
50 | {
51 | public DataElement condition { get; set; }
52 |
53 | public DataElement temp_c { get; set; }
54 |
55 | public DataElement humidity { get; set; }
56 |
57 | public DataElement icon { get; set; }
58 |
59 | public DataElement wind_condition { get; set; }
60 | }
61 |
62 | public class forecast_conditions
63 | {
64 | public DataElement day_of_week { get; set; }
65 |
66 | public DataElement condition { get; set; }
67 |
68 | public DataElement low { get; set; }
69 |
70 | public DataElement high { get; set; }
71 |
72 | public DataElement icon { get; set; }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/RestSharp/Authenticators/JwtAuthenticator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Author: Roman Kravchik
4 | // Based on HttpBasicAuthenticator class by John Sheehan
5 | //
6 | // Licensed under the Apache License, Version 2.0 (the "License");
7 | // you may not use this file except in compliance with the License.
8 | // You may obtain a copy of the License at
9 | //
10 | // http://www.apache.org/licenses/LICENSE-2.0
11 | //
12 | // Unless required by applicable law or agreed to in writing, software
13 | // distributed under the License is distributed on an "AS IS" BASIS,
14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | // See the License for the specific language governing permissions and
16 | // limitations under the License.
17 |
18 | #endregion
19 |
20 | using System;
21 | using System.Linq;
22 |
23 | namespace RestSharp.Authenticators
24 | {
25 | ///
26 | /// JSON WEB TOKEN (JWT) Authenticator class.
27 | /// https://tools.ietf.org/html/draft-ietf-oauth-json-web-token
28 | ///
29 | public class JwtAuthenticator : IAuthenticator
30 | {
31 | private readonly string authHeader;
32 |
33 | public JwtAuthenticator(string accessToken)
34 | {
35 | if (accessToken == null)
36 | {
37 | throw new ArgumentNullException("accessToken");
38 | }
39 |
40 | this.authHeader = string.Format("Bearer {0}", accessToken);
41 | }
42 |
43 | public void Authenticate(IRestClient client, IRestRequest request)
44 | {
45 | // only add the Authorization parameter if it hasn't been added by a previous Execute
46 | if (!request.Parameters.Any(p => p.Type.Equals(ParameterType.HttpHeader) &&
47 | p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))
48 | {
49 | request.AddParameter("Authorization", this.authHeader, ParameterType.HttpHeader);
50 | }
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/RestSharp/Authenticators/HttpBasicAuthenticator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System;
20 | using System.Linq;
21 | using System.Text;
22 |
23 | namespace RestSharp.Authenticators
24 | {
25 | public class HttpBasicAuthenticator : IAuthenticator
26 | {
27 | private readonly string authHeader;
28 |
29 | public HttpBasicAuthenticator(string username, string password)
30 | {
31 | string token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
32 |
33 | this.authHeader = string.Format("Basic {0}", token);
34 | }
35 |
36 | public void Authenticate(IRestClient client, IRestRequest request)
37 | {
38 | // NetworkCredentials always makes two trips, even if with PreAuthenticate,
39 | // it is also unsafe for many partial trust scenarios
40 | // request.Credentials = Credentials;
41 | // thanks TweetSharp!
42 |
43 | // request.Credentials = new NetworkCredential(_username, _password);
44 |
45 | // only add the Authorization parameter if it hasn't been added by a previous Execute
46 | if (!request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))
47 | {
48 | request.AddParameter("Authorization", this.authHeader, ParameterType.HttpHeader);
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/RestSharp/Extensions/ResponseStatusExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net;
3 |
4 | namespace RestSharp.Extensions
5 | {
6 | public static class ResponseStatusExtensions
7 | {
8 | ///
9 | /// Convert a to a instance.
10 | ///
11 | /// The response status.
12 | ///
13 | /// responseStatus
14 | public static WebException ToWebException(this ResponseStatus responseStatus)
15 | {
16 | switch (responseStatus)
17 | {
18 | case ResponseStatus.None:
19 | return new WebException("The request could not be processed.",
20 | #if !SILVERLIGHT
21 | WebExceptionStatus.ServerProtocolViolation
22 | #else
23 | WebExceptionStatus.UnknownError
24 | #endif
25 | );
26 |
27 | case ResponseStatus.Error:
28 | return new WebException("An error occurred while processing the request.",
29 | #if !SILVERLIGHT
30 | WebExceptionStatus.ServerProtocolViolation
31 | #else
32 | WebExceptionStatus.UnknownError
33 | #endif
34 | );
35 |
36 | case ResponseStatus.TimedOut:
37 | return new WebException("The request timed-out.",
38 | #if !SILVERLIGHT
39 | WebExceptionStatus.Timeout
40 | #else
41 | WebExceptionStatus.UnknownError
42 | #endif
43 | );
44 |
45 | case ResponseStatus.Aborted:
46 | return new WebException("The request was aborted.",
47 | #if !SILVERLIGHT
48 | WebExceptionStatus.Timeout
49 | #else
50 | WebExceptionStatus.RequestCanceled
51 | #endif
52 | );
53 |
54 | default:
55 | throw new ArgumentOutOfRangeException("responseStatus");
56 | }
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleClasses/GoogleWeatherWithAttributes.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using RestSharp.Deserializers;
3 |
4 | namespace RestSharp.Tests.SampleClasses
5 | {
6 | public class GoogleWeatherApi
7 | {
8 | public string Version { get; set; }
9 |
10 | public GoogleWeather Weather { get; set; }
11 | }
12 |
13 | public class GoogleWeather : List
14 | {
15 | public string ModuleId { get; set; }
16 |
17 | public string TabId { get; set; }
18 |
19 | public string MobileRow { get; set; }
20 |
21 | public string MobileZipped { get; set; }
22 |
23 | public string Row { get; set; }
24 |
25 | public string Section { get; set; }
26 |
27 | [DeserializeAs(Name = "forecast_information")]
28 | public ForecastInformation Forecast { get; set; }
29 |
30 | [DeserializeAs(Name = "current_conditions")]
31 | public CurrentConditions Current { get; set; }
32 | }
33 |
34 | public class GoogleDataElement
35 | {
36 | public string Data { get; set; }
37 | }
38 |
39 | public class ForecastInformation
40 | {
41 | public GoogleDataElement City { get; set; }
42 |
43 | public GoogleDataElement PostalCode { get; set; }
44 |
45 | public GoogleDataElement ForecastDate { get; set; }
46 |
47 | public GoogleDataElement UnitSystem { get; set; }
48 | }
49 |
50 | public class CurrentConditions
51 | {
52 | public GoogleDataElement Condition { get; set; }
53 |
54 | public GoogleDataElement TempC { get; set; }
55 |
56 | public GoogleDataElement Humidity { get; set; }
57 |
58 | public GoogleDataElement Icon { get; set; }
59 |
60 | public GoogleDataElement WindCondition { get; set; }
61 | }
62 |
63 | public class ForecastConditions
64 | {
65 | public GoogleDataElement DayOfWeek { get; set; }
66 |
67 | public GoogleDataElement Condition { get; set; }
68 |
69 | public GoogleDataElement Low { get; set; }
70 |
71 | public GoogleDataElement High { get; set; }
72 |
73 | public GoogleDataElement Icon { get; set; }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/RestSharp/Compression/ZLib/FlushType.cs:
--------------------------------------------------------------------------------
1 |
2 | #if WINDOWS_PHONE
3 |
4 | using System;
5 | using System.Net;
6 |
7 | namespace RestSharp.Compression.ZLib
8 | {
9 | ///
10 | /// Describes how to flush the current deflate operation.
11 | ///
12 | ///
13 | /// The different FlushType values are useful when using a Deflate in a streaming application.
14 | ///
15 | internal enum FlushType
16 | {
17 | /// No flush at all.
18 | None = 0,
19 |
20 | /// Closes the current block, but doesn't flush it to
21 | /// the output. Used internally only in hypothetical
22 | /// scenarios. This was supposed to be removed by Zlib, but it is
23 | /// still in use in some edge cases.
24 | ///
25 | Partial,
26 |
27 | ///
28 | /// Use this during compression to specify that all pending output should be
29 | /// flushed to the output buffer and the output should be aligned on a byte
30 | /// boundary. You might use this in a streaming communication scenario, so that
31 | /// the decompressor can get all input data available so far. When using this
32 | /// with a ZlibCodec, AvailableBytesIn will be zero after the call if
33 | /// enough output space has been provided before the call. Flushing will
34 | /// degrade compression and so it should be used only when necessary.
35 | ///
36 | Sync,
37 |
38 | ///
39 | /// Use this during compression to specify that all output should be flushed, as
40 | /// with FlushType.Sync, but also, the compression state should be reset
41 | /// so that decompression can restart from this point if previous compressed
42 | /// data has been damaged or if random access is desired. Using
43 | /// FlushType.Full too often can significantly degrade the compression.
44 | ///
45 | Full,
46 |
47 | /// Signals the end of the compression/decompression stream.
48 | Finish,
49 | }
50 | }
51 |
52 | #endif
53 |
--------------------------------------------------------------------------------
/RestSharp.IntegrationTests/FileTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Reflection;
4 | using NUnit.Framework;
5 | using RestSharp.IntegrationTests.Helpers;
6 |
7 | namespace RestSharp.IntegrationTests
8 | {
9 | [TestFixture]
10 | public class FileTests
11 | {
12 | private Uri _baseUrl;
13 | private SimpleServer _server;
14 | private RestClient _client;
15 | private string _path;
16 |
17 | [OneTimeSetUp]
18 | public void SetupServer()
19 | {
20 | _baseUrl = new Uri("http://localhost:8888/");
21 | _path = AppDomain.CurrentDomain.BaseDirectory;
22 | }
23 |
24 | [TearDown]
25 | public void ShutdownServer() => _server.Dispose();
26 |
27 | [SetUp]
28 | public void CreateClient()
29 | {
30 | _client = new RestClient(_baseUrl);
31 | _server = SimpleServer.Create(_baseUrl.AbsoluteUri, c => Handlers.FileHandler(c, _path));
32 | }
33 |
34 | [Test]
35 | public void Handles_Binary_File_Download()
36 | {
37 | RestRequest request = new RestRequest("Assets/Koala.jpg");
38 | byte[] response = _client.DownloadData(request);
39 | byte[] expected = File.ReadAllBytes(_path + "\\Assets\\Koala.jpg");
40 |
41 | Assert.AreEqual(expected, response);
42 | }
43 |
44 | [Test]
45 | public void Writes_Response_To_Stream()
46 | {
47 | string tempFile = Path.GetTempFileName();
48 |
49 | using (FileStream writer = File.OpenWrite(tempFile))
50 | {
51 | RestRequest request = new RestRequest("Assets/Koala.jpg")
52 | {
53 | ResponseWriter = (responseStream) => responseStream.CopyTo(writer)
54 | };
55 | byte[] response = _client.DownloadData(request);
56 |
57 | Assert.Null(response);
58 | }
59 |
60 | byte[] fromTemp = File.ReadAllBytes(tempFile);
61 | byte[] expected = File.ReadAllBytes(_path + "\\Assets\\Koala.jpg");
62 |
63 | Assert.AreEqual(expected, fromTemp);
64 | }
65 | }
66 | }
--------------------------------------------------------------------------------
/RestSharp/Validation/Validate.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System;
20 |
21 | namespace RestSharp.Validation
22 | {
23 | ///
24 | /// Helper methods for validating values
25 | ///
26 | public class Validate
27 | {
28 | ///
29 | /// Validate an integer value is between the specified values (exclusive of min/max)
30 | ///
31 | /// Value to validate
32 | /// Exclusive minimum value
33 | /// Exclusive maximum value
34 | public static void IsBetween(int value, int min, int max)
35 | {
36 | if (value < min || value > max)
37 | {
38 | throw new ArgumentException(string.Format("Value ({0}) is not between {1} and {2}.", value, min, max));
39 | }
40 | }
41 |
42 | ///
43 | /// Validate a string length
44 | ///
45 | /// String to be validated
46 | /// Maximum length of the string
47 | public static void IsValidLength(string value, int maxSize)
48 | {
49 | if (value == null)
50 | {
51 | return;
52 | }
53 |
54 | if (value.Length > maxSize)
55 | {
56 | throw new ArgumentException(string.Format("String is longer than max allowed size ({0}).", maxSize));
57 | }
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/RestSharp/Enum.cs:
--------------------------------------------------------------------------------
1 | #region License
2 | // Copyright 2010 John Sheehan
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 | #endregion
16 |
17 | namespace RestSharp
18 | {
19 | ///
20 | /// Types of parameters that can be added to requests
21 | ///
22 | public enum ParameterType
23 | {
24 | Cookie,
25 | GetOrPost,
26 | UrlSegment,
27 | HttpHeader,
28 | RequestBody,
29 | QueryString
30 | }
31 |
32 | ///
33 | /// Data formats
34 | ///
35 | public enum DataFormat
36 | {
37 | Json,
38 | Xml
39 | }
40 |
41 | ///
42 | /// HTTP method to use when making requests
43 | ///
44 | public enum Method
45 | {
46 | GET,
47 | POST,
48 | PUT,
49 | DELETE,
50 | HEAD,
51 | OPTIONS,
52 | PATCH,
53 | MERGE,
54 | }
55 |
56 | ///
57 | /// Format strings for commonly-used date formats
58 | ///
59 | public struct DateFormat
60 | {
61 | ///
62 | /// .NET format string for ISO 8601 date format
63 | ///
64 | public const string ISO_8601 = "s";
65 |
66 | ///
67 | /// .NET format string for roundtrip date format
68 | ///
69 | public const string ROUND_TRIP = "u";
70 | }
71 |
72 | ///
73 | /// Status for responses (surprised?)
74 | ///
75 | public enum ResponseStatus
76 | {
77 | None,
78 | Completed,
79 | Error,
80 | TimedOut,
81 | Aborted
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/RestSharp/Authenticators/OAuth/Extensions/OAuthExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | #if !WINDOWS_UWP
3 | using System.Security.Cryptography;
4 | #else
5 | using Windows.Security.Cryptography;
6 | using Windows.Security.Cryptography.Core;
7 | using Windows.Storage.Streams;
8 | #endif
9 | using System.Text;
10 |
11 | namespace RestSharp.Authenticators.OAuth.Extensions
12 | {
13 | internal static class OAuthExtensions
14 | {
15 | public static string ToRequestValue(this OAuthSignatureMethod signatureMethod)
16 | {
17 | string value = signatureMethod.ToString()
18 | .ToUpper();
19 | int shaIndex = value.IndexOf("SHA");
20 |
21 | return shaIndex > -1
22 | ? value.Insert(shaIndex, "-")
23 | : value;
24 | }
25 |
26 | public static OAuthSignatureMethod FromRequestValue(this string signatureMethod)
27 | {
28 | switch (signatureMethod)
29 | {
30 | case "HMAC-SHA1":
31 | return OAuthSignatureMethod.HmacSha1;
32 |
33 | case "HMAC-SHA256":
34 | return OAuthSignatureMethod.HmacSha256;
35 |
36 | case "RSA-SHA1":
37 | return OAuthSignatureMethod.RsaSha1;
38 |
39 | default:
40 | return OAuthSignatureMethod.PlainText;
41 | }
42 | }
43 |
44 | #if !WINDOWS_UWP
45 | public static string HashWith(this string input, HashAlgorithm algorithm)
46 | {
47 | byte[] data = Encoding.UTF8.GetBytes(input);
48 | byte[] hash = algorithm.ComputeHash(data);
49 |
50 | return Convert.ToBase64String(hash);
51 | }
52 | #else
53 | public static string HashWith(this string input, HashAlgorithmProvider algorithm)
54 | {
55 | CryptographicHash objHash = algorithm.CreateHash();
56 | IBuffer buffMsg1 = CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf16BE);
57 | objHash.Append(buffMsg1);
58 | IBuffer buffHash1 = objHash.GetValueAndReset();
59 |
60 | return CryptographicBuffer.EncodeToBase64String(buffHash1);
61 | }
62 |
63 | #endif
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/RestSharp.UWP/RestSharp.nuget.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | True
5 | NuGet
6 | C:\Github\RestSharp\RestSharp.UWP\project.lock.json
7 | $(UserProfile)\.nuget\packages\
8 | C:\Users\azima\.nuget\packages\
9 | ProjectJson
10 | 4.3.0
11 |
12 |
13 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath)
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/RestSharp/RestResponseCookie.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace RestSharp
4 | {
5 | public class RestResponseCookie
6 | {
7 | ///
8 | /// Comment of the cookie
9 | ///
10 | public string Comment { get; set; }
11 |
12 | ///
13 | /// Comment of the cookie
14 | ///
15 | public Uri CommentUri { get; set; }
16 |
17 | ///
18 | /// Indicates whether the cookie should be discarded at the end of the session
19 | ///
20 | public bool Discard { get; set; }
21 |
22 | ///
23 | /// Domain of the cookie
24 | ///
25 | public string Domain { get; set; }
26 |
27 | ///
28 | /// Indicates whether the cookie is expired
29 | ///
30 | public bool Expired { get; set; }
31 |
32 | ///
33 | /// Date and time that the cookie expires
34 | ///
35 | public DateTime Expires { get; set; }
36 |
37 | ///
38 | /// Indicates that this cookie should only be accessed by the server
39 | ///
40 | public bool HttpOnly { get; set; }
41 |
42 | ///
43 | /// Name of the cookie
44 | ///
45 | public string Name { get; set; }
46 |
47 | ///
48 | /// Path of the cookie
49 | ///
50 | public string Path { get; set; }
51 |
52 | ///
53 | /// Port of the cookie
54 | ///
55 | public string Port { get; set; }
56 |
57 | ///
58 | /// Indicates that the cookie should only be sent over secure channels
59 | ///
60 | public bool Secure { get; set; }
61 |
62 | ///
63 | /// Date and time the cookie was created
64 | ///
65 | public DateTime TimeStamp { get; set; }
66 |
67 | ///
68 | /// Value of the cookie
69 | ///
70 | public string Value { get; set; }
71 |
72 | ///
73 | /// Version of the cookie
74 | ///
75 | public int Version { get; set; }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/RestSharp.UWP/RestSharp.UWP.nuget.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | True
5 | NuGet
6 | C:\Github\RestSharp\RestSharp.UWP\project.lock.json
7 | $(UserProfile)\.nuget\packages\
8 | C:\Users\azima\.nuget\packages\
9 | ProjectJson
10 | 4.3.1
11 |
12 |
13 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath)
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleData/Lastfm.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 328799
4 | Philip Glass
5 |
6 | Philip Glass
7 | Orchestra and Chorus of Erfurt Theatre
8 | Philip Glass
9 |
10 |
11 | 8777860
12 | Barbican Centre
13 |
14 | London
15 | United Kingdom
16 | Silk Street
17 | EC2Y 8DS
18 |
19 | 51.520099
20 | -0.093609
21 |
22 |
23 | http://www.last.fm/venue/8777860+Barbican+Centre
24 | http://www.barbican.org.uk
25 |
26 | http://userserve-ak.last.fm/serve/34/418510.jpg
27 | http://userserve-ak.last.fm/serve/64/418510.jpg
28 | http://userserve-ak.last.fm/serve/126/418510.jpg
29 | http://userserve-ak.last.fm/serve/252/418510.jpg
30 | http://userserve-ak.last.fm/serve/500/418510/Barbican+Centre.jpg
31 |
32 | Thu, 12 Jun 2008 19:30:00
33 |
34 | http://userserve-ak.last.fm/serve/34/39466081.png
35 | http://userserve-ak.last.fm/serve/64/39466081.png
36 | http://userserve-ak.last.fm/serve/126/39466081.png
37 | http://userserve-ak.last.fm/serve/252/39466081.png
38 | 48
39 | 0
40 | lastfm:event=328799
41 | http://www.last.fm/event/328799+Philip+Glass+at+Barbican+Centre+on+12+June+2008
42 |
43 |
44 | 0
45 |
46 |
47 |
--------------------------------------------------------------------------------
/RestSharp/HttpCookie.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace RestSharp
4 | {
5 | ///
6 | /// Representation of an HTTP cookie
7 | ///
8 | public class HttpCookie
9 | {
10 | ///
11 | /// Comment of the cookie
12 | ///
13 | public string Comment { get; set; }
14 |
15 | ///
16 | /// Comment of the cookie
17 | ///
18 | public Uri CommentUri { get; set; }
19 |
20 | ///
21 | /// Indicates whether the cookie should be discarded at the end of the session
22 | ///
23 | public bool Discard { get; set; }
24 |
25 | ///
26 | /// Domain of the cookie
27 | ///
28 | public string Domain { get; set; }
29 |
30 | ///
31 | /// Indicates whether the cookie is expired
32 | ///
33 | public bool Expired { get; set; }
34 |
35 | ///
36 | /// Date and time that the cookie expires
37 | ///
38 | public DateTime Expires { get; set; }
39 |
40 | ///
41 | /// Indicates that this cookie should only be accessed by the server
42 | ///
43 | public bool HttpOnly { get; set; }
44 |
45 | ///
46 | /// Name of the cookie
47 | ///
48 | public string Name { get; set; }
49 |
50 | ///
51 | /// Path of the cookie
52 | ///
53 | public string Path { get; set; }
54 |
55 | ///
56 | /// Port of the cookie
57 | ///
58 | public string Port { get; set; }
59 |
60 | ///
61 | /// Indicates that the cookie should only be sent over secure channels
62 | ///
63 | public bool Secure { get; set; }
64 |
65 | ///
66 | /// Date and time the cookie was created
67 | ///
68 | public DateTime TimeStamp { get; set; }
69 |
70 | ///
71 | /// Value of the cookie
72 | ///
73 | public string Value { get; set; }
74 |
75 | ///
76 | /// Version of the cookie
77 | ///
78 | public int Version { get; set; }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/RestSharp/Authenticators/NtlmAuthenticator.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | #if FRAMEWORK
20 |
21 | using System;
22 | using System.Net;
23 |
24 | namespace RestSharp.Authenticators
25 | {
26 | ///
27 | /// Tries to Authenticate with the credentials of the currently logged in user, or impersonate a user
28 | ///
29 | public class NtlmAuthenticator : IAuthenticator
30 | {
31 | private readonly ICredentials credentials;
32 |
33 | ///
34 | /// Authenticate with the credentials of the currently logged in user
35 | ///
36 | public NtlmAuthenticator()
37 | : this(CredentialCache.DefaultCredentials) { }
38 |
39 | ///
40 | /// Authenticate by impersonation
41 | ///
42 | ///
43 | ///
44 | public NtlmAuthenticator(string username, string password)
45 | : this(new NetworkCredential(username, password)) { }
46 |
47 | ///
48 | /// Authenticate by impersonation, using an existing ICredentials instance
49 | ///
50 | ///
51 | public NtlmAuthenticator(ICredentials credentials)
52 | {
53 | if (credentials == null)
54 | {
55 | throw new ArgumentNullException("credentials");
56 | }
57 |
58 | this.credentials = credentials;
59 | }
60 |
61 | public void Authenticate(IRestClient client, IRestRequest request)
62 | {
63 | request.Credentials = this.credentials;
64 | }
65 | }
66 | }
67 |
68 | #endif
69 |
--------------------------------------------------------------------------------
/RestSharp/FileParameter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace RestSharp
5 | {
6 | ///
7 | /// Container for files to be uploaded with requests
8 | ///
9 | public class FileParameter
10 | {
11 | ///
12 | /// Creates a file parameter from an array of bytes.
13 | ///
14 | ///The parameter name to use in the request.
15 | ///The data to use as the file's contents.
16 | ///The filename to use in the request.
17 | ///The content type to use in the request.
18 | ///The
19 | public static FileParameter Create(string name, byte[] data, string filename, string contentType)
20 | {
21 | #if FRAMEWORK
22 | long length = data.LongLength;
23 | #else
24 | long length = data.Length;
25 | #endif
26 |
27 | return new FileParameter
28 | {
29 | Writer = s => s.Write(data, 0, data.Length),
30 | FileName = filename,
31 | ContentType = contentType,
32 | ContentLength = length,
33 | Name = name
34 | };
35 | }
36 |
37 | ///
38 | /// Creates a file parameter from an array of bytes.
39 | ///
40 | ///The parameter name to use in the request.
41 | ///The data to use as the file's contents.
42 | ///The filename to use in the request.
43 | ///The using the default content type.
44 | public static FileParameter Create(string name, byte[] data, string filename)
45 | {
46 | return Create(name, data, filename, null);
47 | }
48 |
49 | ///
50 | /// The length of data to be sent
51 | ///
52 | public long ContentLength { get; set; }
53 |
54 | ///
55 | /// Provides raw data for file
56 | ///
57 | public Action Writer { get; set; }
58 |
59 | ///
60 | /// Name of the file to use when uploading
61 | ///
62 | public string FileName { get; set; }
63 |
64 | ///
65 | /// MIME content type of file
66 | ///
67 | public string ContentType { get; set; }
68 |
69 | ///
70 | /// Name of the parameter
71 | ///
72 | public string Name { get; set; }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/RestSharp.Build/RestSharp.Build.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 8.0.30703
7 | 2.0
8 | {CCC30138-3D68-44D8-AF1A-D22F769EE8DC}
9 | Library
10 | Properties
11 | RestSharp.Build
12 | RestSharp.Build
13 | v3.5
14 | 512
15 |
16 |
17 |
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 | false
26 |
27 |
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 | true
35 | false
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
63 |
--------------------------------------------------------------------------------
/RestSharp/IHttpResponse.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Net;
4 |
5 | namespace RestSharp
6 | {
7 | ///
8 | /// HTTP response data
9 | ///
10 | public interface IHttpResponse
11 | {
12 | ///
13 | /// MIME content type of response
14 | ///
15 | string ContentType { get; set; }
16 |
17 | ///
18 | /// Length in bytes of the response content
19 | ///
20 | long ContentLength { get; set; }
21 |
22 | ///
23 | /// Encoding of the response content
24 | ///
25 | string ContentEncoding { get; set; }
26 |
27 | ///
28 | /// String representation of response content
29 | ///
30 | string Content { get; }
31 |
32 | ///
33 | /// HTTP response status code
34 | ///
35 | HttpStatusCode StatusCode { get; set; }
36 |
37 | ///
38 | /// Description of HTTP status returned
39 | ///
40 | string StatusDescription { get; set; }
41 |
42 | ///
43 | /// Response content
44 | ///
45 | byte[] RawBytes { get; set; }
46 |
47 | ///
48 | /// The URL that actually responded to the content (different from request if redirected)
49 | ///
50 | Uri ResponseUri { get; set; }
51 |
52 | ///
53 | /// HttpWebResponse.Server
54 | ///
55 | string Server { get; set; }
56 |
57 | ///
58 | /// Headers returned by server with the response
59 | ///
60 | IList Headers { get; }
61 |
62 | ///
63 | /// Cookies returned by server with the response
64 | ///
65 | IList Cookies { get; }
66 |
67 | ///
68 | /// Status of the request. Will return Error for transport errors.
69 | /// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead
70 | ///
71 | ResponseStatus ResponseStatus { get; set; }
72 |
73 | ///
74 | /// Transport or other non-HTTP error generated while attempting request
75 | ///
76 | string ErrorMessage { get; set; }
77 |
78 | ///
79 | /// Exception thrown when error is encountered.
80 | ///
81 | Exception ErrorException { get; set; }
82 |
83 | ///
84 | /// The HTTP protocol version (1.0, 1.1, etc)
85 | ///
86 | /// Only set when underlying framework supports it.
87 | Version ProtocolVersion { get; set; }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/RestSharp.Tests/OAuthTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Globalization;
3 | using System.Threading;
4 | using NUnit.Framework;
5 | using RestSharp.Authenticators.OAuth;
6 | using RestSharp.Authenticators.OAuth.Extensions;
7 |
8 | namespace RestSharp.Tests
9 | {
10 | [TestFixture]
11 | public class OAuthTests
12 | {
13 | public OAuthTests()
14 | {
15 | Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
16 | Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture;
17 | }
18 |
19 | [Test]
20 | [TestCase("abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz")]
21 | [TestCase("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")]
22 | [TestCase("0123456789", "0123456789")]
23 | [TestCase("-._~", "-._~")]
24 | [TestCase(" !\"#$%&'()*+,", "%20%21%22%23%24%25%26%27%28%29%2A%2B%2C")]
25 | [TestCase("%$%", "%25%24%25")]
26 | [TestCase("%", "%25")]
27 | [TestCase("/:;<=>?@", "%2F%3A%3B%3C%3D%3E%3F%40")]
28 | [TestCase("\x00\x01\a\b\f\n\r\t\v", @"%00%01%07%08%0C%0A%0D%09%0B")]
29 | public void UrlStrictEncode_Encodes_Correctly(string value, string expected)
30 | {
31 | string actual = OAuthTools.UrlEncodeStrict(value);
32 |
33 | Assert.AreEqual(expected, actual);
34 | }
35 |
36 | [Test]
37 | [TestCase("1234", "%31%32%33%34")]
38 | [TestCase("\x00\x01\x02\x03", "%00%01%02%03")]
39 | [TestCase("\r\n\t", "%0D%0A%09")]
40 | public void PercentEncode_Encodes_Correctly(string value, string expected)
41 | {
42 | string actual = value.PercentEncode();
43 |
44 | Assert.AreEqual(expected, actual);
45 | }
46 |
47 | [Test]
48 | [TestCase("The quick brown fox jumps over the lazy dog", "rVL90tHhGt0eQ0TCITY74nVL22P%2FltlWS7WvJXpECPs%3D")]
49 | [TestCase("The quick\tbrown\nfox\rjumps\r\nover\t\tthe\n\nlazy\r\n\r\ndog", "C%2B2RY0Hna6VrfK1crCkU%2FV1e0ECoxoDh41iOOdmEMx8%3D")]
50 | [TestCase("", "%2BnkCwZfv%2FQVmBbNZsPKbBT3kAg3JtVn3f3YMBtV83L8%3D")]
51 | [TestCase(" !\"#$%&'()*+,", "xcTgWGBVZaw%2Bilg6kjWAGt%2FhCcsVBMMe1CcDEnxnh8Y%3D")]
52 | public void HmacSha256_Hashes_Correctly(string value, string expected)
53 | {
54 | string consumerSecret = "12345678";
55 | string actual = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha256, value, consumerSecret);
56 |
57 | Assert.AreEqual(expected, actual);
58 | }
59 |
60 | [Test]
61 | public void HmacSha256_Does_Not_Accept_Nulls()
62 | {
63 | string consumerSecret = "12345678";
64 | Assert.That(() => OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha256, null, consumerSecret),
65 | Throws.TypeOf());
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/RestSharp.IntegrationTests/Helpers/SimpleServer.cs:
--------------------------------------------------------------------------------
1 | namespace RestSharp.IntegrationTests.Helpers
2 | {
3 | using System;
4 | using System.Net;
5 | using System.Security;
6 | using System.Threading;
7 |
8 | public class SimpleServer : IDisposable
9 | {
10 | private readonly HttpListener _listener;
11 |
12 | private Action _handler;
13 |
14 | private Thread _thread;
15 |
16 | private SimpleServer(HttpListener listener, Action handler)
17 | {
18 | _listener = listener;
19 | _handler = handler;
20 | }
21 |
22 | public static SimpleServer Create(string url, Action handler = null,
23 | AuthenticationSchemes authenticationSchemes = AuthenticationSchemes.Anonymous)
24 | {
25 | var listener = new HttpListener
26 | {
27 | Prefixes = {url},
28 | AuthenticationSchemes = authenticationSchemes
29 | };
30 | var server = new SimpleServer(listener, handler);
31 |
32 | server.Start();
33 |
34 | return server;
35 | }
36 |
37 | public void SetHandler(Action handler) =>
38 | _handler = handler;
39 |
40 | private void Start()
41 | {
42 | if (_listener.IsListening)
43 | {
44 | return;
45 | }
46 |
47 | _listener.Start();
48 |
49 | _thread = new Thread(() =>
50 | {
51 | HttpListenerContext context = _listener.GetContext();
52 | _handler(context);
53 | context.Response.Close();
54 | })
55 | {
56 | Name = "WebServer"
57 | };
58 |
59 | _thread.Start();
60 | }
61 |
62 | public void Dispose()
63 | {
64 | try
65 | {
66 | _thread.Abort();
67 | }
68 | catch (ThreadStateException threadStateException)
69 | {
70 | Console.Error.WriteLine("Issue aborting thread - {0}.", threadStateException.Message);
71 | }
72 | catch (SecurityException securityException)
73 | {
74 | Console.Error.WriteLine("Issue aborting thread - {0}.", securityException.Message);
75 | }
76 |
77 | if (_listener.IsListening)
78 | {
79 | try
80 | {
81 | _listener.Stop();
82 | }
83 | catch (ObjectDisposedException objectDisposedException)
84 | {
85 | Console.Error.WriteLine("Issue stopping listener - {0}", objectDisposedException.Message);
86 | }
87 | }
88 |
89 | _listener.Close();
90 | }
91 | }
92 | }
--------------------------------------------------------------------------------
/RestSharp.IntegrationTests/CompressionTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO.Compression;
3 | using System.Net;
4 | using NUnit.Framework;
5 | using RestSharp.IntegrationTests.Helpers;
6 |
7 | namespace RestSharp.IntegrationTests
8 | {
9 | [TestFixture]
10 | public class CompressionTests
11 | {
12 | [Test]
13 | public void Can_Handle_Gzip_Compressed_Content()
14 | {
15 | Uri baseUrl = new Uri("http://localhost:8888/");
16 |
17 | using (SimpleServer.Create(baseUrl.AbsoluteUri, GzipEchoValue("This is some gzipped content")))
18 | {
19 | RestClient client = new RestClient(baseUrl);
20 | RestRequest request = new RestRequest("");
21 | IRestResponse response = client.Execute(request);
22 |
23 | Assert.AreEqual("This is some gzipped content", response.Content);
24 | }
25 | }
26 |
27 | [Test]
28 | public void Can_Handle_Deflate_Compressed_Content()
29 | {
30 | Uri baseUrl = new Uri("http://localhost:8888/");
31 |
32 | using (SimpleServer.Create(baseUrl.AbsoluteUri, DeflateEchoValue("This is some deflated content")))
33 | {
34 | RestClient client = new RestClient(baseUrl);
35 | RestRequest request = new RestRequest("");
36 | IRestResponse response = client.Execute(request);
37 |
38 | Assert.AreEqual("This is some deflated content", response.Content);
39 | }
40 | }
41 |
42 | [Test]
43 | public void Can_Handle_Uncompressed_Content()
44 | {
45 | Uri baseUrl = new Uri("http://localhost:8888/");
46 |
47 | using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.EchoValue("This is some sample content")))
48 | {
49 | RestClient client = new RestClient(baseUrl);
50 | RestRequest request = new RestRequest("");
51 | IRestResponse response = client.Execute(request);
52 |
53 | Assert.AreEqual("This is some sample content", response.Content);
54 | }
55 | }
56 |
57 | private static Action GzipEchoValue(string value) =>
58 | context =>
59 | {
60 | context.Response.Headers.Add("Content-encoding", "gzip");
61 |
62 | using (GZipStream gzip = new GZipStream(context.Response.OutputStream, CompressionMode.Compress, true))
63 | {
64 | gzip.WriteStringUtf8(value);
65 | }
66 | };
67 |
68 | private static Action DeflateEchoValue(string value) =>
69 | context =>
70 | {
71 | context.Response.Headers.Add("Content-encoding", "deflate");
72 |
73 | using (DeflateStream gzip =
74 | new DeflateStream(context.Response.OutputStream, CompressionMode.Compress, true))
75 | {
76 | gzip.WriteStringUtf8(value);
77 | }
78 | };
79 | }
80 | }
--------------------------------------------------------------------------------
/RestSharp/Serializers/DotNetXmlSerializer.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 | using System.Text;
3 | using System.Xml.Serialization;
4 |
5 | namespace RestSharp.Serializers
6 | {
7 | ///
8 | /// Wrapper for System.Xml.Serialization.XmlSerializer.
9 | ///
10 | public class DotNetXmlSerializer : ISerializer
11 | {
12 | ///
13 | /// Default constructor, does not specify namespace
14 | ///
15 | public DotNetXmlSerializer()
16 | {
17 | this.ContentType = "application/xml";
18 | this.Encoding = Encoding.UTF8;
19 | }
20 |
21 | ///
22 | /// Specify the namespaced to be used when serializing
23 | ///
24 | /// XML namespace
25 | public DotNetXmlSerializer(string @namespace)
26 | : this()
27 | {
28 | this.Namespace = @namespace;
29 | }
30 |
31 | ///
32 | /// Serialize the object as XML
33 | ///
34 | /// Object to serialize
35 | /// XML as string
36 | public string Serialize(object obj)
37 | {
38 | XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
39 |
40 | ns.Add(string.Empty, this.Namespace);
41 |
42 | System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
43 | EncodingStringWriter writer = new EncodingStringWriter(this.Encoding);
44 |
45 | serializer.Serialize(writer, obj, ns);
46 |
47 | return writer.ToString();
48 | }
49 |
50 | ///
51 | /// Name of the root element to use when serializing
52 | ///
53 | public string RootElement { get; set; }
54 |
55 | ///
56 | /// XML namespace to use when serializing
57 | ///
58 | public string Namespace { get; set; }
59 |
60 | ///
61 | /// Format string to use when serializing dates
62 | ///
63 | public string DateFormat { get; set; }
64 |
65 | ///
66 | /// Content type for serialized content
67 | ///
68 | public string ContentType { get; set; }
69 |
70 | ///
71 | /// Encoding for serialized content
72 | ///
73 | public Encoding Encoding { get; set; }
74 |
75 | ///
76 | /// Need to subclass StringWriter in order to override Encoding
77 | ///
78 | private class EncodingStringWriter : StringWriter
79 | {
80 | private readonly Encoding encoding;
81 |
82 | public EncodingStringWriter(Encoding encoding)
83 | {
84 | this.encoding = encoding;
85 | }
86 |
87 | public override Encoding Encoding
88 | {
89 | get { return this.encoding; }
90 | }
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/RestSharp.IntegrationTests/Helpers/Handlers.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Linq;
4 | using System.Net;
5 | using System.Reflection;
6 |
7 | namespace RestSharp.IntegrationTests.Helpers
8 | {
9 | public static class Handlers
10 | {
11 | ///
12 | /// Echoes the request input back to the output.
13 | ///
14 | public static void Echo(HttpListenerContext context)
15 | {
16 | context.Request.InputStream.CopyTo(context.Response.OutputStream);
17 | }
18 |
19 | ///
20 | /// Echoes the given value back to the output.
21 | ///
22 | public static Action EchoValue(string value)
23 | {
24 | return ctx => ctx.Response.OutputStream.WriteStringUtf8(value);
25 | }
26 |
27 | ///
28 | /// Response to a request like this: http://localhost:8888/assets/koala.jpg
29 | /// by streaming the file located at "assets\koala.jpg" back to the client.
30 | ///
31 | public static void FileHandler(HttpListenerContext context, string path)
32 | {
33 | var pathToFile = Path.Combine(path, Path.Combine(context.Request.Url.Segments.Select(s => s.Replace("/", ""))
34 | .ToArray()));
35 |
36 | using (var reader = new StreamReader(pathToFile))
37 | {
38 | reader.BaseStream.CopyTo(context.Response.OutputStream);
39 | }
40 | }
41 |
42 | ///
43 | /// T should be a class that implements methods whose names match the urls being called, and take one parameter, an HttpListenerContext.
44 | /// e.g.
45 | /// urls exercised: "http://localhost:8888/error" and "http://localhost:8888/get_list"
46 | ///
47 | /// class MyHandler
48 | /// {
49 | /// void error(HttpListenerContext ctx)
50 | /// {
51 | /// // do something interesting here
52 | /// }
53 | ///
54 | /// void get_list(HttpListenerContext ctx)
55 | /// {
56 | /// // do something interesting here
57 | /// }
58 | /// }
59 | ///
60 | public static Action Generic() where T : new()
61 | {
62 | return ctx =>
63 | {
64 | string methodName = ctx.Request.Url.Segments.Last();
65 | MethodInfo method = typeof(T).GetMethod(methodName,
66 | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
67 |
68 | if (method.IsStatic)
69 | {
70 | method.Invoke(null, new object[] { ctx });
71 | }
72 | else
73 | {
74 | method.Invoke(new T(), new object[] { ctx });
75 | }
76 | };
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RestSharp - Simple .NET REST Client
2 |
3 | [](https://ci.appveyor.com/project/hallem/restsharp)
4 |
5 | [](https://gitter.im/RestSharp/RestSharp?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
6 |
7 | ### [Official Site][1] - [@RestSharp][2]
8 |
9 | ### License: Apache License 2.0
10 |
11 | ### Features
12 |
13 | * Supports .NET 3.5+, Mono, Mono for Android, UWP
14 | * Easy installation using [NuGet](http://nuget.org/packages/RestSharp) for most .NET flavors
15 | * Supports strong naming using [NuGet](http://nuget.org/packages/RestSharpSigned) for most .NET flavors
16 | * Automatic XML and JSON deserialization
17 | * Supports custom serialization and deserialization via ISerializer and IDeserializer
18 | * Fuzzy element name matching ('product_id' in XML/JSON will match C# property named 'ProductId')
19 | * Automatic detection of type of content returned
20 | * GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE supported
21 | * Other non-standard HTTP methods also supported
22 | * OAuth 1, OAuth 2, Basic, NTLM and Parameter-based Authenticators included
23 | * Supports custom authentication schemes via IAuthenticator
24 | * Multi-part form/file uploads
25 | * T4 Helper to generate C# classes from an XML document
26 |
27 | ```csharp
28 | var client = new RestClient("http://example.com");
29 | // client.Authenticator = new HttpBasicAuthenticator(username, password);
30 |
31 | var request = new RestRequest("resource/{id}", Method.POST);
32 | request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
33 | request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
34 |
35 | // add parameters for all properties on an object
36 | request.AddObject(object);
37 |
38 | // or just whitelisted properties
39 | request.AddObject(object, "PersonId", "Name", ...);
40 |
41 | // easily add HTTP Headers
42 | request.AddHeader("header", "value");
43 |
44 | // add files to upload (works with compatible verbs)
45 | request.AddFile("file", path);
46 |
47 | // execute the request
48 | IRestResponse response = client.Execute(request);
49 | var content = response.Content; // raw content as string
50 |
51 | // or automatically deserialize result
52 | // return content type is sniffed but can be explicitly set via RestClient.AddHandler();
53 | IRestResponse response2 = client.Execute(request);
54 | var name = response2.Data.Name;
55 |
56 | // or download and save file to disk
57 | client.DownloadData(request).SaveAs(path);
58 |
59 | // easy async support
60 | client.ExecuteAsync(request, response => {
61 | Console.WriteLine(response.Content);
62 | });
63 |
64 | // async with deserialization
65 | var asyncHandle = client.ExecuteAsync(request, response => {
66 | Console.WriteLine(response.Data.Name);
67 | });
68 |
69 | // abort the request on demand
70 | asyncHandle.Abort();
71 | ```
72 |
73 | [1]: http://restsharp.org
74 | [2]: http://twitter.com/RestSharp
75 | [3]: http://groups.google.com/group/RestSharp
76 |
--------------------------------------------------------------------------------
/RestSharp.Build/RestSharp.Build.Signed.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 8.0.30703
7 | 2.0
8 | {60CF35B5-ABE3-47E4-BA0C-0ABAF1618475}
9 | Library
10 | Properties
11 | RestSharp.Build
12 | RestSharp.Build
13 | v3.5
14 | 512
15 |
16 |
17 |
18 | true
19 | full
20 | false
21 | bin\DebugSigned\
22 | obj\DebugSigned\
23 | TRACE;DEBUG;SIGNED
24 | prompt
25 | 4
26 | false
27 |
28 |
29 | pdbonly
30 | true
31 | bin\ReleaseSigned\
32 | obj\ReleaseSigned\
33 | TRACE;SIGNED
34 | prompt
35 | 4
36 | true
37 | false
38 |
39 |
40 | true
41 |
42 |
43 | ..\RestSharp.snk
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 | RestSharp.snk
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
76 |
--------------------------------------------------------------------------------
/RestSharp.Tests/RestRequestTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Globalization;
3 | using System.Linq;
4 | using System.Threading;
5 | using NUnit.Framework;
6 |
7 | namespace RestSharp.Tests
8 | {
9 | public class RestRequestTests
10 | {
11 | public RestRequestTests()
12 | {
13 | Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
14 | Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture;
15 | }
16 |
17 | [Test]
18 | public void Can_Add_Object_With_IntegerArray_property()
19 | {
20 | RestRequest request = new RestRequest();
21 |
22 | request.AddObject(new { Items = new [] { 2, 3, 4 } });
23 | }
24 |
25 | [Test]
26 | public void Cannot_Set_Empty_Host_Header()
27 | {
28 | RestRequest request = new RestRequest();
29 | ArgumentException exception = Assert.Throws(() => request.AddHeader("Host", string.Empty));
30 |
31 | Assert.AreEqual("value", exception.ParamName);
32 | }
33 |
34 | [Test]
35 | [TestCase("http://localhost")]
36 | [TestCase("hostname 1234")]
37 | [TestCase("-leading.hyphen.not.allowed")]
38 | [TestCase("bad:port")]
39 | [TestCase(" no.leading.white-space")]
40 | [TestCase("no.trailing.white-space ")]
41 | [TestCase(".leading.dot.not.allowed")]
42 | [TestCase("double.dots..not.allowed")]
43 | [TestCase(".")]
44 | [TestCase(".:2345")]
45 | [TestCase(":5678")]
46 | [TestCase("")]
47 | [TestCase("foo:bar:baz")]
48 | public void Cannot_Set_Invalid_Host_Header(string value)
49 | {
50 | RestRequest request = new RestRequest();
51 | ArgumentException exception = Assert.Throws(() => request.AddHeader("Host", value));
52 |
53 | Assert.AreEqual("value", exception.ParamName);
54 | }
55 |
56 | [Test]
57 | [TestCase("localhost")]
58 | [TestCase("localhost:1234")]
59 | [TestCase("host.local")]
60 | [TestCase("anotherhost.local:2345")]
61 | [TestCase("www.w3.org")]
62 | [TestCase("www.w3.org:3456")]
63 | [TestCase("8.8.8.8")]
64 | [TestCase("a.1.b.2")]
65 | [TestCase("10.20.30.40:1234")]
66 | [TestCase("0host")]
67 | [TestCase("hypenated-hostname")]
68 | [TestCase("multi--hyphens")]
69 | public void Can_Set_Valid_Host_Header(string value)
70 | {
71 | RestRequest request = new RestRequest();
72 |
73 | Assert.DoesNotThrow(() => request.AddHeader("Host", value));
74 | }
75 |
76 | [Test]
77 | [TestCase(1, "1")]
78 | [TestCase("1", "1")]
79 | [TestCase("entity", "entity")]
80 | public void Can_Add_Object_To_UrlSegment(object value, string expectedValue)
81 | {
82 | const string ParameterName = "Id";
83 | RestRequest request = new RestRequest();
84 | request.AddUrlSegment(ParameterName, value);
85 |
86 | var parameter = request.Parameters.FirstOrDefault(x => x.Name.Equals(ParameterName));
87 | Assert.IsNotNull(parameter);
88 | Assert.AreEqual(expectedValue, parameter.Value.ToString());
89 | Assert.AreEqual(ParameterType.UrlSegment, parameter.Type);
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleData/ListWithAttributes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CA92d4405c9237c4ea04b56cbda88e128c
6 | Fri, 13 Aug 2010 01:16:22 +0000
7 | Fri, 13 Aug 2010 01:16:22 +0000
8 |
9 | AC5ef877a5fe4238be081ea6f3c44186f3
10 | +15304551166
11 | +15105555555
12 | PNe2d8e63b37f46f2adb16f228afdb9058
13 | queued
14 | Thu, 12 Aug 2010 01:37:05 +0000
15 | Thu, 12 Aug 2010 01:37:40 +0000
16 |
17 |
18 | outbound-api
19 |
20 | 2010-04-01
21 |
22 |
23 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c
24 |
25 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c/Notifications
26 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c/Recordings
27 |
28 |
29 |
30 | CA12345
31 | Fri, 13 Aug 2010 01:16:22 +0000
32 | Fri, 13 Aug 2010 01:16:22 +0000
33 |
34 | AC5ef877a5fe4238be081ea6f3c44186f3
35 | +15304551166
36 | +15105555555
37 | PNe2d8e63b37f46f2adb16f228afdb9058
38 | queued
39 | Thu, 12 Aug 2010 01:37:05 +0000
40 | Thu, 12 Aug 2010 01:37:40 +0000
41 |
42 |
43 | outbound-api
44 |
45 | 2010-04-01
46 |
47 |
48 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c
49 |
50 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c/Notifications
51 | /2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls/CA92d4405c9237c4ea04b56cbda88e128c/Recordings
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/RestSharp/Authenticators/OAuth/Extensions/CollectionExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Collections.Specialized;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace RestSharp.Authenticators.OAuth.Extensions
8 | {
9 | internal static class CollectionExtensions
10 | {
11 | public static IEnumerable AsEnumerable(this T item)
12 | {
13 | return new[] { item };
14 | }
15 |
16 | public static IEnumerable And(this T item, T other)
17 | {
18 | return new[] { item, other };
19 | }
20 |
21 | public static IEnumerable And(this IEnumerable items, T item)
22 | {
23 | foreach (T i in items)
24 | {
25 | yield return i;
26 | }
27 |
28 | yield return item;
29 | }
30 |
31 | public static TK TryWithKey(this IDictionary dictionary, T key)
32 | {
33 | return dictionary.ContainsKey(key)
34 | ? dictionary[key]
35 | : default(TK);
36 | }
37 |
38 | public static IEnumerable ToEnumerable(this object[] items) where T : class
39 | {
40 | return items.Select(item => item as T);
41 | }
42 |
43 | public static void ForEach(this IEnumerable items, Action action)
44 | {
45 | foreach (T item in items)
46 | {
47 | action(item);
48 | }
49 | }
50 |
51 | #if !WINDOWS_PHONE && !SILVERLIGHT
52 | public static void AddRange(this IDictionary collection, NameValueCollection range)
53 | {
54 | foreach (string key in range.AllKeys)
55 | {
56 | collection.Add(key, range[key]);
57 | }
58 | }
59 |
60 | public static string ToQueryString(this NameValueCollection collection)
61 | {
62 | StringBuilder sb = new StringBuilder();
63 |
64 | if (collection.Count > 0)
65 | {
66 | sb.Append("?");
67 | }
68 |
69 | int count = 0;
70 |
71 | foreach (string key in collection.AllKeys)
72 | {
73 | sb.AppendFormat("{0}={1}", key, collection[key].UrlEncode());
74 | count++;
75 |
76 | if (count >= collection.Count)
77 | {
78 | continue;
79 | }
80 |
81 | sb.Append("&");
82 | }
83 |
84 | return sb.ToString();
85 | }
86 | #endif
87 |
88 | public static string Concatenate(this WebParameterCollection collection, string separator, string spacer)
89 | {
90 | StringBuilder sb = new StringBuilder();
91 | int total = collection.Count;
92 | int count = 0;
93 |
94 | foreach (WebPair item in collection)
95 | {
96 | sb.Append(item.Name);
97 | sb.Append(separator);
98 | sb.Append(item.Value);
99 |
100 | count++;
101 |
102 | if (count < total)
103 | {
104 | sb.Append(spacer);
105 | }
106 | }
107 |
108 | return sb.ToString();
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Globalization;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace RestSharp.Authenticators.OAuth.Extensions
8 | {
9 | internal static class StringExtensions
10 | {
11 | public static bool IsNullOrBlank(this string value)
12 | {
13 | return string.IsNullOrEmpty(value) ||
14 | (!string.IsNullOrEmpty(value) && value.Trim() == string.Empty);
15 | }
16 |
17 | public static bool EqualsIgnoreCase(this string left, string right)
18 | {
19 | return string.Compare(left, right, StringComparison.OrdinalIgnoreCase) == 0;
20 | }
21 |
22 | public static bool EqualsAny(this string input, params string[] args)
23 | {
24 | return args.Aggregate(false, (current, arg) => current | input.Equals(arg));
25 | }
26 |
27 | public static string FormatWith(this string format, params object[] args)
28 | {
29 | return string.Format(format, args);
30 | }
31 |
32 | public static string FormatWithInvariantCulture(this string format, params object[] args)
33 | {
34 | return string.Format(CultureInfo.InvariantCulture, format, args);
35 | }
36 |
37 | public static string Then(this string input, string value)
38 | {
39 | return string.Concat(input, value);
40 | }
41 |
42 | public static string UrlEncode(this string value)
43 | {
44 | // [DC] This is more correct than HttpUtility; it escapes spaces as %20, not +
45 | return Uri.EscapeDataString(value);
46 | }
47 |
48 | public static string UrlDecode(this string value)
49 | {
50 | return Uri.UnescapeDataString(value);
51 | }
52 |
53 | public static Uri AsUri(this string value)
54 | {
55 | return new Uri(value);
56 | }
57 |
58 | public static string ToBase64String(this byte[] input)
59 | {
60 | return Convert.ToBase64String(input);
61 | }
62 |
63 | public static byte[] GetBytes(this string input)
64 | {
65 | return Encoding.UTF8.GetBytes(input);
66 | }
67 |
68 | public static string PercentEncode(this string s)
69 | {
70 | byte[] bytes = s.GetBytes();
71 | StringBuilder sb = new StringBuilder();
72 |
73 | foreach (byte b in bytes)
74 | {
75 | sb.Append(string.Format("%{0:X2}", b));
76 | }
77 |
78 | return sb.ToString();
79 | }
80 |
81 | public static IDictionary ParseQueryString(this string query)
82 | {
83 | // [DC]: This method does not URL decode, and cannot handle decoded input
84 | if (query.StartsWith("?"))
85 | {
86 | query = query.Substring(1);
87 | }
88 |
89 | if (query.Equals(string.Empty))
90 | {
91 | return new Dictionary();
92 | }
93 |
94 | string[] parts = query.Split('&');
95 |
96 | return parts.Select(part => part.Split('='))
97 | .ToDictionary(pair => pair[0], pair => pair[1]);
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleClasses/twitter.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using RestSharp.Deserializers;
3 |
4 | namespace RestSharp.Tests.SampleClasses
5 | {
6 | public class status
7 | {
8 | public bool truncated { get; set; }
9 |
10 | public string created_at { get; set; }
11 |
12 | public string source { get; set; }
13 |
14 | public bool favorited { get; set; }
15 |
16 | public string in_reply_to_user_id { get; set; }
17 |
18 | public string in_reply_to_status_id { get; set; }
19 |
20 | public string in_reply_to_screen_name { get; set; }
21 |
22 | // ignore contributors for now
23 | public user user { get; set; }
24 |
25 | // ignore geo
26 | public long id { get; set; }
27 |
28 | public string text { get; set; }
29 | }
30 |
31 | public class user
32 | {
33 | public string url { get; set; }
34 |
35 | public string description { get; set; }
36 |
37 | public string profile_text_color { get; set; }
38 |
39 | public int followers_count { get; set; }
40 |
41 | public int statuses_count { get; set; }
42 |
43 | public bool geo_enabled { get; set; }
44 |
45 | public string profile_background_image_url { get; set; }
46 |
47 | public bool notifications { get; set; }
48 |
49 | public string created_at { get; set; }
50 |
51 | public int friends_count { get; set; }
52 |
53 | public string profile_link_color { get; set; }
54 |
55 | public bool contributors_enabled { get; set; }
56 |
57 | public bool profile_background_tile { get; set; }
58 |
59 | public int favourites_count { get; set; }
60 |
61 | public string profile_background_color { get; set; }
62 |
63 | public string profile_image_url { get; set; }
64 |
65 | public string lang { get; set; }
66 |
67 | public bool verified { get; set; }
68 |
69 | public string profile_sidebar_fill_color { get; set; }
70 |
71 | public bool @protected { get; set; }
72 |
73 | public string screen_name { get; set; }
74 |
75 | public bool following { get; set; }
76 |
77 | public string location { get; set; }
78 |
79 | public string name { get; set; }
80 |
81 | public string time_zone { get; set; }
82 |
83 | public string profile_sidebar_border_color { get; set; }
84 |
85 | public long id { get; set; }
86 |
87 | public int utc_offset { get; set; }
88 | }
89 |
90 | public class StatusList : List { }
91 |
92 | public class complexStatus
93 | {
94 | public bool truncated { get; set; }
95 |
96 | public string created_at { get; set; }
97 |
98 | public string source { get; set; }
99 |
100 | public bool favorited { get; set; }
101 |
102 | public string in_reply_to_user_id { get; set; }
103 |
104 | public string in_reply_to_status_id { get; set; }
105 |
106 | public string in_reply_to_screen_name { get; set; }
107 |
108 | // ignore contributors for now
109 | [DeserializeAs(Name = "user.following")]
110 | public bool follow { get; set; }
111 |
112 | // ignore geo
113 | public long id { get; set; }
114 |
115 | public string text { get; set; }
116 | }
117 |
118 | public class StatusComplexList : List { }
119 | }
120 |
--------------------------------------------------------------------------------
/RestSharp/Serializers/SerializeAsAttribute.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System;
20 | using RestSharp.Extensions;
21 | using System.Globalization;
22 |
23 | namespace RestSharp.Serializers
24 | {
25 | ///
26 | /// Allows control how class and property names and values are serialized by XmlSerializer
27 | /// Currently not supported with the JsonSerializer
28 | /// When specified at the property level the class-level specification is overridden
29 | ///
30 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false)]
31 | public sealed class SerializeAsAttribute : Attribute
32 | {
33 | public SerializeAsAttribute()
34 | {
35 | this.NameStyle = NameStyle.AsIs;
36 | this.Index = int.MaxValue;
37 | this.Culture = CultureInfo.InvariantCulture;
38 | }
39 |
40 | ///
41 | /// The name to use for the serialized element
42 | ///
43 | public string Name { get; set; }
44 |
45 | ///
46 | /// Sets the value to be serialized as an Attribute instead of an Element
47 | ///
48 | public bool Attribute { get; set; }
49 |
50 | ///
51 | /// The culture to use when serializing
52 | ///
53 | public CultureInfo Culture { get; set; }
54 |
55 | ///
56 | /// Transforms the casing of the name based on the selected value.
57 | ///
58 | public NameStyle NameStyle { get; set; }
59 |
60 | ///
61 | /// The order to serialize the element. Default is int.MaxValue.
62 | ///
63 | public int Index { get; set; }
64 |
65 | ///
66 | /// Called by the attribute when NameStyle is speficied
67 | ///
68 | /// The string to transform
69 | /// String
70 | public string TransformName(string input)
71 | {
72 | string name = this.Name ?? input;
73 |
74 | switch (this.NameStyle)
75 | {
76 | case NameStyle.CamelCase:
77 | return name.ToCamelCase(this.Culture);
78 |
79 | case NameStyle.PascalCase:
80 | return name.ToPascalCase(this.Culture);
81 |
82 | case NameStyle.LowerCase:
83 | return name.ToLower();
84 | }
85 |
86 | return input;
87 | }
88 | }
89 |
90 | ///
91 | /// Options for transforming casing of element names
92 | ///
93 | public enum NameStyle
94 | {
95 | AsIs,
96 | CamelCase,
97 | LowerCase,
98 | PascalCase
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/RestSharp.Tests/SampleClasses/eventful.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace RestSharp.Tests.SampleClasses
5 | {
6 | public class VenueSearch
7 | {
8 | public string total_items { get; set; }
9 |
10 | public string page_size { get; set; }
11 |
12 | public string page_count { get; set; }
13 |
14 | public string page_number { get; set; }
15 |
16 | public string page_items { get; set; }
17 |
18 | public string first_item { get; set; }
19 |
20 | public string last_item { get; set; }
21 |
22 | public string search_time { get; set; }
23 |
24 | public List venues { get; set; }
25 | }
26 |
27 | public class PerformerSearch
28 | {
29 | public string total_items { get; set; }
30 |
31 | public string page_size { get; set; }
32 |
33 | public string page_count { get; set; }
34 |
35 | public string page_number { get; set; }
36 |
37 | public string page_items { get; set; }
38 |
39 | public string first_item { get; set; }
40 |
41 | public string last_item { get; set; }
42 |
43 | public string search_time { get; set; }
44 |
45 | public List performers { get; set; }
46 | }
47 |
48 | public class Performer
49 | {
50 | public string id { get; set; }
51 |
52 | public string url { get; set; }
53 |
54 | public string name { get; set; }
55 |
56 | public string short_bio { get; set; }
57 |
58 | public DateTime? created { get; set; }
59 |
60 | public string creator { get; set; }
61 |
62 | public string demand_count { get; set; }
63 |
64 | public string demand_member_count { get; set; }
65 |
66 | public string event_count { get; set; }
67 |
68 | public ServiceImage image { get; set; }
69 | }
70 |
71 | public class Venue
72 | {
73 | public string id { get; set; }
74 |
75 | public string url { get; set; }
76 |
77 | public string name { get; set; }
78 |
79 | public string venue_name { get; set; }
80 |
81 | public string description { get; set; }
82 |
83 | public string venue_type { get; set; }
84 |
85 | public string address { get; set; }
86 |
87 | public string city_name { get; set; }
88 |
89 | public string region_name { get; set; }
90 |
91 | public string postal_code { get; set; }
92 |
93 | public string country_name { get; set; }
94 |
95 | public string longitude { get; set; }
96 |
97 | public string latitude { get; set; }
98 |
99 | public string event_count { get; set; }
100 | }
101 |
102 | public class ServiceImage
103 | {
104 | public ServiceImage1 thumb { get; set; }
105 |
106 | public ServiceImage1 small { get; set; }
107 |
108 | public ServiceImage1 medium { get; set; }
109 | }
110 |
111 | public class ServiceImage1
112 | {
113 | public string url { get; set; }
114 |
115 | public string width { get; set; }
116 |
117 | public string height { get; set; }
118 | }
119 |
120 | public class Event
121 | {
122 | public string id { get; set; }
123 |
124 | public string url { get; set; }
125 |
126 | public string title { get; set; }
127 |
128 | public string description { get; set; }
129 |
130 | public string start_time { get; set; }
131 |
132 | public string venue_name { get; set; }
133 |
134 | public string venue_id { get; set; }
135 |
136 | public List performers { get; set; }
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/.nuget/NuGet.targets:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $(MSBuildProjectDirectory)\..\
5 |
6 |
7 | $([System.IO.Path]::Combine($(SolutionDir), ".nuget"))
8 | $([System.IO.Path]::Combine($(ProjectDir), "packages.config"))
9 | $([System.IO.Path]::Combine($(SolutionDir), "packages"))
10 |
11 |
12 | $(SolutionDir).nuget
13 | packages.config
14 | $(SolutionDir)packages
15 |
16 |
17 | $(NuGetToolsPath)\nuget.exe
18 | "$(NuGetExePath)"
19 | mono --runtime=v4.0.30319 $(NuGetExePath)
20 |
21 | $(TargetDir.Trim('\\'))
22 |
23 |
24 | ""
25 |
26 |
27 | false
28 |
29 |
30 | false
31 |
32 |
33 | $(NuGetCommand) install "$(PackagesConfig)" -source $(PackageSources) -o "$(PackagesDir)"
34 | $(NuGetCommand) pack "$(ProjectPath)" -p Configuration=$(Configuration) -o "$(PackageOutputDir)" -symbols
35 |
36 |
37 |
38 | RestorePackages;
39 | $(BuildDependsOn);
40 |
41 |
42 |
43 |
44 | $(BuildDependsOn);
45 | BuildPackage;
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
57 |
58 |
61 |
62 |
63 |
64 |
66 |
67 |
70 |
71 |
--------------------------------------------------------------------------------
/RestSharp/IRestResponse.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Net;
4 |
5 | namespace RestSharp
6 | {
7 | ///
8 | /// Container for data sent back from API
9 | ///
10 | public interface IRestResponse
11 | {
12 | ///
13 | /// The RestRequest that was made to get this RestResponse
14 | ///
15 | ///
16 | /// Mainly for debugging if ResponseStatus is not OK
17 | ///
18 | IRestRequest Request { get; set; }
19 |
20 | ///
21 | /// MIME content type of response
22 | ///
23 | string ContentType { get; set; }
24 |
25 | ///
26 | /// Length in bytes of the response content
27 | ///
28 | long ContentLength { get; set; }
29 |
30 | ///
31 | /// Encoding of the response content
32 | ///
33 | string ContentEncoding { get; set; }
34 |
35 | ///
36 | /// String representation of response content
37 | ///
38 | string Content { get; set; }
39 |
40 | ///
41 | /// HTTP response status code
42 | ///
43 | HttpStatusCode StatusCode { get; set; }
44 |
45 | ///
46 | /// Whether or not the response status code indicates success
47 | ///
48 | bool IsSuccessful { get; }
49 |
50 | ///
51 | /// Description of HTTP status returned
52 | ///
53 | string StatusDescription { get; set; }
54 |
55 | ///
56 | /// Response content
57 | ///
58 | byte[] RawBytes { get; set; }
59 |
60 | ///
61 | /// The URL that actually responded to the content (different from request if redirected)
62 | ///
63 | Uri ResponseUri { get; set; }
64 |
65 | ///
66 | /// HttpWebResponse.Server
67 | ///
68 | string Server { get; set; }
69 |
70 | ///
71 | /// Cookies returned by server with the response
72 | ///
73 | IList Cookies { get; }
74 |
75 | ///
76 | /// Headers returned by server with the response
77 | ///
78 | IList Headers { get; }
79 |
80 | ///
81 | /// Status of the request. Will return Error for transport errors.
82 | /// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead
83 | ///
84 | ResponseStatus ResponseStatus { get; set; }
85 |
86 | ///
87 | /// Transport or other non-HTTP error generated while attempting request
88 | ///
89 | string ErrorMessage { get; set; }
90 |
91 | ///
92 | /// Exceptions thrown during the request, if any.
93 | ///
94 | /// Will contain only network transport or framework exceptions thrown during the request.
95 | /// HTTP protocol errors are handled by RestSharp and will not appear here.
96 | Exception ErrorException { get; set; }
97 |
98 | ///
99 | /// The HTTP protocol version (1.0, 1.1, etc)
100 | ///
101 | /// Only set when underlying framework supports it.
102 | Version ProtocolVersion { get; set; }
103 | }
104 |
105 | ///
106 | /// Container for data sent back from API including deserialized data
107 | ///
108 | /// Type of data to deserialize to
109 | public interface IRestResponse : IRestResponse
110 | {
111 | ///
112 | /// Deserialized entity data
113 | ///
114 | T Data { get; set; }
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/RestSharp/IHttp.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System;
20 | using System.Collections.Generic;
21 | using System.IO;
22 | using System.Net;
23 | using System.Text;
24 |
25 | #if FRAMEWORK
26 | using System.Net.Cache;
27 | using System.Net.Security;
28 | using System.Security.Cryptography.X509Certificates;
29 | #endif
30 |
31 | namespace RestSharp
32 | {
33 | public interface IHttp
34 | {
35 | Action ResponseWriter { get; set; }
36 |
37 | CookieContainer CookieContainer { get; set; }
38 |
39 | ICredentials Credentials { get; set; }
40 |
41 | ///
42 | /// Always send a multipart/form-data request - even when no Files are present.
43 | ///
44 | bool AlwaysMultipartFormData { get; set; }
45 |
46 | string UserAgent { get; set; }
47 |
48 | int Timeout { get; set; }
49 |
50 | int ReadWriteTimeout { get; set; }
51 |
52 | #if !SILVERLIGHT
53 | bool FollowRedirects { get; set; }
54 |
55 | bool Pipelined { get; set; }
56 | #endif
57 |
58 | #if FRAMEWORK
59 | X509CertificateCollection ClientCertificates { get; set; }
60 |
61 | int? MaxRedirects { get; set; }
62 | #endif
63 |
64 | bool UseDefaultCredentials { get; set; }
65 |
66 | Encoding Encoding { get; set; }
67 |
68 | IList Headers { get; }
69 |
70 | IList Parameters { get; }
71 |
72 | IList Files { get; }
73 |
74 | IList Cookies { get; }
75 |
76 | string RequestBody { get; set; }
77 |
78 | string RequestContentType { get; set; }
79 |
80 | bool PreAuthenticate { get; set; }
81 |
82 | #if FRAMEWORK
83 | RequestCachePolicy CachePolicy { get; set; }
84 | #endif
85 |
86 | ///
87 | /// An alternative to RequestBody, for when the caller already has the byte array.
88 | ///
89 | byte[] RequestBodyBytes { get; set; }
90 |
91 | Uri Url { get; set; }
92 |
93 | HttpWebRequest DeleteAsync(Action action);
94 |
95 | HttpWebRequest GetAsync(Action action);
96 |
97 | HttpWebRequest HeadAsync(Action action);
98 |
99 | HttpWebRequest OptionsAsync(Action action);
100 |
101 | HttpWebRequest PostAsync(Action action);
102 |
103 | HttpWebRequest PutAsync(Action action);
104 |
105 | HttpWebRequest PatchAsync(Action action);
106 |
107 | HttpWebRequest MergeAsync(Action action);
108 |
109 | HttpWebRequest AsPostAsync(Action action, string httpMethod);
110 |
111 | HttpWebRequest AsGetAsync(Action action, string httpMethod);
112 |
113 | #if FRAMEWORK
114 | HttpResponse Delete();
115 |
116 | HttpResponse Get();
117 |
118 | HttpResponse Head();
119 |
120 | HttpResponse Options();
121 |
122 | HttpResponse Post();
123 |
124 | HttpResponse Put();
125 |
126 | HttpResponse Patch();
127 |
128 | HttpResponse Merge();
129 |
130 | HttpResponse AsPost(string httpMethod);
131 |
132 | HttpResponse AsGet(string httpMethod);
133 |
134 | IWebProxy Proxy { get; set; }
135 | #endif
136 | #if NET45
137 | RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; }
138 | #endif
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/RestSharp.Build/NuSpecUpdateTask.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Linq;
4 | using System.Reflection;
5 | using System.Xml.Linq;
6 | using Microsoft.Build.Utilities;
7 |
8 | namespace RestSharp.Build
9 | {
10 | public class NuSpecUpdateTask : Task
11 | {
12 | private Assembly assembly;
13 |
14 | public string Id { get; private set; }
15 |
16 | public string Authors { get; private set; }
17 |
18 | public string Description { get; private set; }
19 |
20 | public string Version { get; private set; }
21 |
22 | public string SpecFile { get; set; }
23 |
24 | public string SourceAssemblyFile { get; set; }
25 |
26 | public NuSpecUpdateTask() : this(null) { }
27 |
28 | public NuSpecUpdateTask(Assembly assembly)
29 | {
30 | this.assembly = assembly;
31 | }
32 |
33 | public override bool Execute()
34 | {
35 | if (string.IsNullOrEmpty(this.SpecFile))
36 | return false;
37 |
38 | var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SourceAssemblyFile);
39 | this.assembly = this.assembly ?? Assembly.LoadFile(path);
40 |
41 | var name = this.assembly.GetName();
42 |
43 | #if SIGNED
44 | this.Id = name.Name + "Signed";
45 | #else
46 | this.Id = name.Name;
47 | #endif
48 | this.Authors = GetAuthors(this.assembly);
49 | this.Description = GetDescription(this.assembly);
50 | this.Version = GetVersion(this.assembly);
51 |
52 | this.GenerateComputedSpecFile();
53 |
54 | return true;
55 | }
56 |
57 | private void GenerateComputedSpecFile()
58 | {
59 | var doc = XDocument.Load(this.SpecFile);
60 | var metaNode = doc.Descendants("metadata").First();
61 |
62 | ReplaceToken(metaNode, "id", this.Id);
63 | ReplaceToken(metaNode, "authors", this.Authors);
64 | ReplaceToken(metaNode, "owners", this.Authors);
65 | ReplaceToken(metaNode, "description", this.Description);
66 | ReplaceToken(metaNode, "version", this.Version);
67 | #if SIGNED
68 | doc.Save(this.SpecFile.Replace(".nuspec", "-signed-computed.nuspec"));
69 | #else
70 | doc.Save(this.SpecFile.Replace(".nuspec", "-computed.nuspec"));
71 | #endif
72 | }
73 |
74 | private static void ReplaceToken(XContainer metaNode, XName name, string value)
75 | {
76 | var node = metaNode.Element(name);
77 | var token = string.Format("${0}$", name.ToString().TrimEnd('s'));
78 |
79 | if (name.ToString().Equals("owners"))
80 | {
81 | token = "$author$";
82 | }
83 |
84 | if (node != null && node.Value.Equals(token, StringComparison.OrdinalIgnoreCase))
85 | {
86 | node.SetValue(value);
87 | }
88 | }
89 |
90 | private static string GetDescription(ICustomAttributeProvider asm)
91 | {
92 | return GetAttribute(asm).Description;
93 | }
94 |
95 | private static string GetAuthors(ICustomAttributeProvider asm)
96 | {
97 | return GetAttribute(asm).Company;
98 | }
99 |
100 | private static string GetVersion(Assembly asm)
101 | {
102 | var version = asm.GetName().Version.ToString();
103 | var attr = GetAttribute(asm);
104 |
105 | if (attr != null)
106 | {
107 | version = attr.InformationalVersion;
108 | }
109 |
110 | return version;
111 | }
112 |
113 | private static TAttr GetAttribute(ICustomAttributeProvider asm) where TAttr : Attribute
114 | {
115 | var attrs = asm.GetCustomAttributes(typeof(TAttr), false);
116 |
117 | if (attrs.Length > 0)
118 | {
119 | return attrs[0] as TAttr;
120 | }
121 |
122 | return null;
123 | }
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/RestSharp/HttpResponse.cs:
--------------------------------------------------------------------------------
1 | #region License
2 |
3 | // Copyright 2010 John Sheehan
4 | //
5 | // Licensed under the Apache License, Version 2.0 (the "License");
6 | // you may not use this file except in compliance with the License.
7 | // You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing, software
12 | // distributed under the License is distributed on an "AS IS" BASIS,
13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | // See the License for the specific language governing permissions and
15 | // limitations under the License.
16 |
17 | #endregion
18 |
19 | using System;
20 | using System.Collections.Generic;
21 | using System.Net;
22 | using RestSharp.Extensions;
23 |
24 | namespace RestSharp
25 | {
26 | ///
27 | /// HTTP response data
28 | ///
29 | public class HttpResponse : IHttpResponse
30 | {
31 | private string content;
32 |
33 | ///
34 | /// Default constructor
35 | ///
36 | public HttpResponse()
37 | {
38 | this.ResponseStatus = ResponseStatus.None;
39 | this.Headers = new List();
40 | this.Cookies = new List();
41 | }
42 |
43 | ///
44 | /// MIME content type of response
45 | ///
46 | public string ContentType { get; set; }
47 |
48 | ///
49 | /// Length in bytes of the response content
50 | ///
51 | public long ContentLength { get; set; }
52 |
53 | ///
54 | /// Encoding of the response content
55 | ///
56 | public string ContentEncoding { get; set; }
57 |
58 | ///
59 | /// Lazy-loaded string representation of response content
60 | ///
61 | public string Content
62 | {
63 | get { return this.content ?? (this.content = this.RawBytes.AsString()); }
64 | }
65 |
66 | ///
67 | /// HTTP response status code
68 | ///
69 | public HttpStatusCode StatusCode { get; set; }
70 |
71 | ///
72 | /// Description of HTTP status returned
73 | ///
74 | public string StatusDescription { get; set; }
75 |
76 | ///
77 | /// Response content
78 | ///
79 | public byte[] RawBytes { get; set; }
80 |
81 | ///
82 | /// The URL that actually responded to the content (different from request if redirected)
83 | ///
84 | public Uri ResponseUri { get; set; }
85 |
86 | ///
87 | /// HttpWebResponse.Server
88 | ///
89 | public string Server { get; set; }
90 |
91 | ///
92 | /// Headers returned by server with the response
93 | ///
94 | public IList Headers { get; private set; }
95 |
96 | ///
97 | /// Cookies returned by server with the response
98 | ///
99 | public IList Cookies { get; private set; }
100 |
101 | ///
102 | /// Status of the request. Will return Error for transport errors.
103 | /// HTTP errors will still return ResponseStatus.Completed, check StatusCode instead
104 | ///
105 | public ResponseStatus ResponseStatus { get; set; }
106 |
107 | ///
108 | /// Transport or other non-HTTP error generated while attempting request
109 | ///
110 | public string ErrorMessage { get; set; }
111 |
112 | ///
113 | /// Exception thrown when error is encountered.
114 | ///
115 | public Exception ErrorException { get; set; }
116 |
117 | ///
118 | /// The HTTP protocol version (1.0, 1.1, etc)
119 | ///
120 | /// Only set when underlying framework supports it.
121 | public Version ProtocolVersion { get; set; }
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/RestSharp/RestClient.Sync.cs:
--------------------------------------------------------------------------------
1 | #if FRAMEWORK
2 |
3 | using System;
4 |
5 | namespace RestSharp
6 | {
7 | public partial class RestClient
8 | {
9 | ///
10 | /// Executes the specified request and downloads the response data
11 | ///
12 | /// Request to execute
13 | /// Response data
14 | public byte[] DownloadData(IRestRequest request)
15 | {
16 | IRestResponse response = this.Execute(request);
17 |
18 | return response.RawBytes;
19 | }
20 |
21 | ///
22 | /// Executes the request and returns a response, authenticating if needed
23 | ///
24 | /// Request to be executed
25 | /// RestResponse
26 | public virtual IRestResponse Execute(IRestRequest request)
27 | {
28 | string method = Enum.GetName(typeof(Method), request.Method);
29 |
30 | switch (request.Method)
31 | {
32 | case Method.POST:
33 | case Method.PUT:
34 | case Method.PATCH:
35 | case Method.MERGE:
36 | return this.Execute(request, method, DoExecuteAsPost);
37 |
38 | default:
39 | return this.Execute(request, method, DoExecuteAsGet);
40 | }
41 | }
42 |
43 | public IRestResponse ExecuteAsGet(IRestRequest request, string httpMethod)
44 | {
45 | return this.Execute(request, httpMethod, DoExecuteAsGet);
46 | }
47 |
48 | public IRestResponse ExecuteAsPost(IRestRequest request, string httpMethod)
49 | {
50 | request.Method = Method.POST; // Required by RestClient.BuildUri...
51 |
52 | return this.Execute(request, httpMethod, DoExecuteAsPost);
53 | }
54 |
55 | private IRestResponse Execute(IRestRequest request, string httpMethod,
56 | Func getResponse)
57 | {
58 | this.AuthenticateIfNeeded(this, request);
59 |
60 | IRestResponse response = new RestResponse();
61 |
62 | try
63 | {
64 | IHttp http = this.HttpFactory.Create();
65 |
66 | this.ConfigureHttp(request, http);
67 |
68 | response = ConvertToRestResponse(request, getResponse(http, httpMethod));
69 | response.Request = request;
70 | response.Request.IncreaseNumAttempts();
71 | }
72 | catch (Exception ex)
73 | {
74 | response.ResponseStatus = ResponseStatus.Error;
75 | response.ErrorMessage = ex.Message;
76 | response.ErrorException = ex;
77 | }
78 |
79 | return response;
80 | }
81 |
82 | private static HttpResponse DoExecuteAsGet(IHttp http, string method)
83 | {
84 | return http.AsGet(method);
85 | }
86 |
87 | private static HttpResponse DoExecuteAsPost(IHttp http, string method)
88 | {
89 | return http.AsPost(method);
90 | }
91 |
92 | ///
93 | /// Executes the specified request and deserializes the response content using the appropriate content handler
94 | ///
95 | /// Target deserialization type
96 | /// Request to execute
97 | /// RestResponse[[T]] with deserialized data in Data property
98 | public virtual IRestResponse Execute(IRestRequest request) where T : new()
99 | {
100 | return this.Deserialize(request, this.Execute(request));
101 | }
102 |
103 | public IRestResponse ExecuteAsGet(IRestRequest request, string httpMethod) where T : new()
104 | {
105 | return this.Deserialize(request, this.ExecuteAsGet(request, httpMethod));
106 | }
107 |
108 | public IRestResponse ExecuteAsPost(IRestRequest request, string httpMethod) where T : new()
109 | {
110 | return this.Deserialize(request, this.ExecuteAsPost(request, httpMethod));
111 | }
112 | }
113 | }
114 |
115 | #endif
116 |
--------------------------------------------------------------------------------
/RestSharp.Tests/JwtAuthTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Globalization;
4 | using System.Linq;
5 | using System.Threading;
6 | using NUnit.Framework;
7 | using RestSharp.Authenticators;
8 |
9 | namespace RestSharp.Tests
10 | {
11 | [TestFixture]
12 | public class JwtAuthTests
13 | {
14 | private readonly string testJwt;
15 |
16 | private readonly string expectedAuthHeaderContent;
17 |
18 | public JwtAuthTests()
19 | {
20 | Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
21 | Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture;
22 |
23 | this.testJwt = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9" + "." +
24 | "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQo" +
25 | "gImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ" + "." +
26 | "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
27 |
28 | this.expectedAuthHeaderContent = string.Format("Bearer {0}", this.testJwt);
29 | }
30 |
31 | [Test]
32 | public void Throw_Argument_Null_Exception()
33 | {
34 | ArgumentNullException exception = Assert.Throws(() => new JwtAuthenticator(null));
35 |
36 | Assert.AreEqual("accessToken", exception.ParamName);
37 | }
38 |
39 | [Test]
40 | public void Can_Set_ValidFormat_Auth_Header()
41 | {
42 | RestClient client = new RestClient { Authenticator = new JwtAuthenticator(this.testJwt) };
43 | RestRequest request = new RestRequest();
44 |
45 | //In real case client.Execute(request) will invoke Authenticate method
46 | client.Authenticator.Authenticate(client, request);
47 |
48 | Parameter authParam = request.Parameters.Single(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase));
49 |
50 | Assert.True(authParam.Type == ParameterType.HttpHeader);
51 | Assert.AreEqual(this.expectedAuthHeaderContent, authParam.Value);
52 | }
53 |
54 | [Test]
55 | public void Check_Only_Header_Authorization()
56 | {
57 | RestClient client = new RestClient { Authenticator = new JwtAuthenticator(this.testJwt) };
58 | RestRequest request = new RestRequest();
59 |
60 | //Paranoic server needs "two-factor authentication": jwt header and query param key for example
61 | request.AddParameter("Authorization", "manualAuth", ParameterType.QueryString);
62 |
63 | //In real case client.Execute(request) will invoke Authenticate method
64 | client.Authenticator.Authenticate(client, request);
65 |
66 | List paramList = request.Parameters.FindAll(p => p.Name.Equals("Authorization"));
67 |
68 | Assert.AreEqual(2, paramList.Count);
69 |
70 | Parameter queryAuthParam = paramList.Single(p => p.Type.Equals(ParameterType.QueryString));
71 | Parameter headerAuthParam = paramList.Single(p => p.Type.Equals(ParameterType.HttpHeader));
72 |
73 | Assert.AreEqual("manualAuth", queryAuthParam.Value);
74 | Assert.AreEqual(this.expectedAuthHeaderContent, headerAuthParam.Value);
75 | }
76 |
77 | [Test]
78 | public void Set_Auth_Header_Only_Once()
79 | {
80 | RestClient client = new RestClient();
81 | RestRequest request = new RestRequest();
82 |
83 | request.AddHeader("Authorization", this.expectedAuthHeaderContent);
84 |
85 | client.Authenticator = new JwtAuthenticator("second_header_auth_token");
86 |
87 | //In real case client.Execute(...) will invoke Authenticate method
88 | client.Authenticator.Authenticate(client, request);
89 |
90 | List paramList = request.Parameters.FindAll(p => p.Name.Equals("Authorization"));
91 |
92 | Assert.AreEqual(1, paramList.Count);
93 |
94 | Parameter authParam = paramList[0];
95 |
96 | Assert.True(authParam.Type == ParameterType.HttpHeader);
97 | Assert.AreEqual(this.expectedAuthHeaderContent, authParam.Value);
98 | Assert.AreNotEqual("second_header_auth_token", authParam.Value);
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/RestSharp.IntegrationTests/RequestHeadTests.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Specialized;
2 | using System.Linq;
3 | using System.Net;
4 | using NUnit.Framework;
5 | using RestSharp.IntegrationTests.Helpers;
6 |
7 | namespace RestSharp.IntegrationTests
8 | {
9 | [TestFixture]
10 | public class RequestHeadTests
11 | {
12 | private const string BASE_URL = "http://localhost:8888/";
13 |
14 | [SetUp]
15 | public void SetupRequestHeadTests()
16 | {
17 | RequestHeadCapturer.Initialize();
18 | }
19 |
20 | [Test]
21 | public void Does_Not_Pass_Default_Credentials_When_Server_Does_Not_Negotiate()
22 | {
23 | const Method httpMethod = Method.GET;
24 |
25 | using (SimpleServer.Create(BASE_URL, Handlers.Generic()))
26 | {
27 | RestClient client = new RestClient(BASE_URL);
28 | RestRequest request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod)
29 | {
30 | UseDefaultCredentials = true
31 | };
32 |
33 | client.Execute(request);
34 |
35 | Assert.NotNull(RequestHeadCapturer.CapturedHeaders);
36 |
37 | string[] keys = RequestHeadCapturer.CapturedHeaders.Keys.Cast()
38 | .ToArray();
39 |
40 | Assert.False(keys.Contains("Authorization"),
41 | "Authorization header was present in HTTP request from client, even though server does not use the Negotiate scheme");
42 | }
43 | }
44 |
45 | [Test]
46 | public void Passes_Default_Credentials_When_UseDefaultCredentials_Is_True()
47 | {
48 | const Method httpMethod = Method.GET;
49 |
50 | using (SimpleServer.Create(BASE_URL, Handlers.Generic(), AuthenticationSchemes.Negotiate))
51 | {
52 | RestClient client = new RestClient(BASE_URL);
53 | RestRequest request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod)
54 | {
55 | UseDefaultCredentials = true
56 | };
57 | IRestResponse response = client.Execute(request);
58 |
59 | Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
60 | Assert.NotNull(RequestHeadCapturer.CapturedHeaders);
61 |
62 | string[] keys = RequestHeadCapturer.CapturedHeaders.Keys.Cast()
63 | .ToArray();
64 |
65 | Assert.True(keys.Contains("Authorization"),
66 | "Authorization header not present in HTTP request from client, even though UseDefaultCredentials = true");
67 | }
68 | }
69 |
70 | [Test]
71 | public void Does_Not_Pass_Default_Credentials_When_UseDefaultCredentials_Is_False()
72 | {
73 | const Method httpMethod = Method.GET;
74 |
75 | using (SimpleServer.Create(BASE_URL, Handlers.Generic(), AuthenticationSchemes.Negotiate))
76 | {
77 | RestClient client = new RestClient(BASE_URL);
78 | RestRequest request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod)
79 | {
80 | // UseDefaultCredentials is currently false by default,
81 | // but to make the test more robust in case that ever
82 | // changes, it's better to explicitly set it here.
83 | UseDefaultCredentials = false
84 | };
85 | IRestResponse response = client.Execute(request);
86 |
87 | Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
88 | Assert.Null(RequestHeadCapturer.CapturedHeaders);
89 | }
90 | }
91 |
92 | private class RequestHeadCapturer
93 | {
94 | public const string RESOURCE = "Capture";
95 |
96 | public static NameValueCollection CapturedHeaders { get; set; }
97 |
98 | public static void Initialize()
99 | {
100 | CapturedHeaders = null;
101 | }
102 |
103 | public static void Capture(HttpListenerContext context)
104 | {
105 | HttpListenerRequest request = context.Request;
106 |
107 | CapturedHeaders = request.Headers;
108 | }
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------