Exemplo n.º 1
0
        private static async Task MainAsync(string[] args)
        {
            using (var environment = ExampleEnvironment.Start())
            {
                var baseUri = environment.GetResourceWebService <Resource.Api.Startup>().BaseUri;

                /*
                 * RequestDto and ResponseDto refer to the Request Body and Response Body.
                 * The reason in which it is specified as a DTO is in reference to
                 * Data Transfer Object. This is a POCO (Plain Old C Object) where the
                 * class consists of ONLY properties with a get and set. For example:
                 *
                 *  public class MyDto
                 *  {
                 *       public string Message { get; set; }
                 *       public int Id { get; set; }
                 *  }
                 *
                 *  DTOs are a fantastic way to transfer data across layers of an application.
                 *  That's why in RestWell, we refer to the objects that represent the request
                 *  and response bodies as DTOs.
                 *
                 *  You can create your DTOs to match one-for-one with the body and allow the
                 *  framework to auto-magically know how to serialize and deserialize your DTO.
                 *
                 *  If complete utter control is your thing, no problem. You can mark up your
                 *  request with Newtonsoft.Json annotations to better describe how to
                 *  serialize/deserialize the request/response body into it's corresponding DTO.
                 */

                using (var proxy = new Proxy())
                {
                    /*
                     * Set the Request DTO and Response DTO types for the ProxyRequestBuilder
                     * Note: If a request does not have a Request Body or a Response Body you
                     *       can use System.Missing as the type to specify that there is no body
                     */
                    var proxyRequest = ProxyRequestBuilder <ExampleRequestDto, ExampleResponseDto>
                                       .CreateBuilder(baseUri, HttpRequestMethod.Get)
                                       .AppendToRoute("api/example/body")
                                       .Accept("application/json")
                                       // Set the Request DTO
                                       .SetRequestDto(new ExampleRequestDto {
                        Message = "Hello World"
                    })
                                       .Build();

                    var proxyResponse = await proxy.InvokeAsync(proxyRequest).ConfigureAwait(false);

                    if (proxyResponse.IsSuccessfulStatusCode)
                    {
                        Console.WriteLine("Proxy Response Body:");
                        Console.WriteLine($"\tDTO Type: {proxyResponse.ResponseDto.GetType().Name}");
                        Console.WriteLine($"\tResponse Message: {proxyResponse.ResponseDto.Message}");
                    }
                }
            }

            Console.ReadKey();
        }
Exemplo n.º 2
0
        public async Task ReturnAResponseFromAnyProxyRequest()
        {
            // Setup your mocked stuff
            var mockedProxyRequest = ProxyRequestBuilder <string[]>
                                     .CreateBuilder("https://www.this.is/fake", HttpRequestMethod.Get)
                                     .AppendToRoute("api/example")
                                     .Accept("application/json")
                                     .Build();

            var mockedProxyResponse = new ProxyResponse <string[]>
            {
                IsSuccessfulStatusCode = true,
                StatusCode             = HttpStatusCode.OK,
                ResponseDto            = new[] { "Mocked Value From Any Request 1", "Mocked Value From Any Request 2" }
            };

            // Create and configure TestProxy
            var testProxy = new TestProxy();

            testProxy.WhenIReceiveAnyRequest <Missing, string[]>().ThenIShouldReturnThisResponse(mockedProxyResponse);

            // Use the TetProxy in the class that needs it
            var classThatUsesProxy          = new ClassThatUsesProxy(testProxy);
            var methodThatUsesProxyResponse = await classThatUsesProxy.MethodThatUsesProxyAsync(mockedProxyRequest).ConfigureAwait(false);

            Assert.Equal("Mocked Value From Any Request 1", methodThatUsesProxyResponse[0]);
            Assert.Equal("Mocked Value From Any Request 2", methodThatUsesProxyResponse[1]);
        }
Exemplo n.º 3
0
        public WhyNotBothProxyRequest(string baseUri, ExampleRequestDto requestDto)
        {
            var proxyRequest = ProxyRequestBuilder <ExampleRequestDto, ExampleResponseDto>
                               .CreateBuilder("https://www.this.is/a/base/url/api", HttpRequestMethod.Get)
                               .AppendToRoute($"controller")
                               .Authorization("Basic", "Username:Password")
                               .Accept("application/json")
                               .AddHeader("x-customHeader", "value1", "value2", "value3")
                               .AddPathArguments("arg1", "arg2")
                               .AddQueryParameter("queryParam1", "value")
                               .SetRequestDto(new ExampleRequestDto {
                Message = "Hello World"
            })
                               .Build();

            this.Headers           = proxyRequest.Headers;
            this.HttpRequestMethod = proxyRequest.HttpRequestMethod;
            this.RequestDto        = proxyRequest.RequestDto;
            this.RequestUri        = proxyRequest.RequestUri;
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Index()
        {
            HomeModel model = new HomeModel();

            using (var environment = ExampleEnvironment.Start())
            {
                var baseUri = environment.GetResourceWebService <RestWell.Examples.Resource.Api.Startup>().BaseUri;

                var proxyRequest = ProxyRequestBuilder <string[]>
                                   .CreateBuilder(baseUri, HttpRequestMethod.Get)
                                   .AppendToRoute("api/example")
                                   .Accept("application/json")
                                   .Build();

                // Using the inject ProxyConfiguration
                using (var proxy = new Proxy(this.injectedProxyConfiguration))
                {
                    var proxyResponseForInjectedProxyConfiguration = await this.injectedProxy.InvokeAsync(proxyRequest);

                    if (proxyResponseForInjectedProxyConfiguration.IsSuccessfulStatusCode)
                    {
                        model.ValuesFromInjectedProxyConfiguration = proxyResponseForInjectedProxyConfiguration.ResponseDto;
                    }
                }

                // Using the injected Proxy
                var proxyResponseForInjectedProxy = await this.injectedProxy.InvokeAsync(proxyRequest);

                if (proxyResponseForInjectedProxy.IsSuccessfulStatusCode)
                {
                    model.ValuesFromInjectedProxy = proxyResponseForInjectedProxy.ResponseDto;
                }
            }

            return(View(model));
        }
        private static async Task MainAsync(string[] args)
        {
            using (var environment = ExampleEnvironment.Start())
            {
                var baseUri = environment.GetResourceWebService <Resource.Api.Startup>().BaseUri;

                /*
                 * Configuring the proxy allows you to customize the proxy's behavior.
                 * For example, you can inject your own delegating handler into the
                 * request pipeline or set default request headers for every request!
                 */

                #region Setting a Default Request Header

                // In order to configure the proxy, you need to create a ProxyConfiguration using the ProxyConfigurationBuilder
                var proxyConfigurationBuilder = ProxyConfigurationBuilder.CreateBuilder();

                /*
                 * The ProxyConfigurationBuilder exposes a few things to use that we can take
                 * advantage of for every request. For example, if we always want
                 * to Accept application/json, we can set the default Accept header to
                 * always be application/json
                 */
                proxyConfigurationBuilder.UseDefaultAcceptHeader(new MediaTypeWithQualityHeaderValue("application/json"));

                // Now, we use the ProxyConfigurationBuilder.Build() to create a ProxyConfiguration
                var proxyConfiguration = proxyConfigurationBuilder.Build();

                // Now, you use the ProxyConfiguration when creating the Proxy to tell the Proxy how to be configured
                using (var proxy = new Proxy(proxyConfiguration))
                {
                    // Notice on this request we did not use the Accept() method to add an accept header
                    var proxyRequest = ProxyRequestBuilder <string[]>
                                       .CreateBuilder(baseUri, HttpRequestMethod.Get)
                                       .AppendToRoute("api/example")
                                       .Build();

                    var proxyResponse = await proxy.InvokeAsync(proxyRequest).ConfigureAwait(false);

                    if (proxyResponse.IsSuccessfulStatusCode)
                    {
                        // Let's see what the accept header looks like
                        var requestHeaders = proxyResponse.RequestHeaders;
                        var acceptHeader   = requestHeaders.Accept;

                        Console.WriteLine("The Accept Header Value:");
                        Console.WriteLine($"\t{acceptHeader}");

                        Console.WriteLine();

                        // Show the API response
                        var valuesArray = proxyResponse.ResponseDto;
                        Writer.WriteValues(valuesArray);
                    }
                }

                #endregion

                Console.WriteLine("\n==========\n");

                #region Overriding a Default Request Header

                /*
                 * But what if we want application/xml as the default, but for a certain request we want application/json?
                 * Great question, you can use the ProxyRequest to override the ProxyConfiguration's default header values.
                 */
                proxyConfiguration = ProxyConfigurationBuilder.CreateBuilder()
                                     // Setting the default Accept header to "application/xml"
                                     .UseDefaultAcceptHeader(new MediaTypeWithQualityHeaderValue("application/xml"))
                                     .Build();

                using (var proxy = new Proxy(proxyConfiguration))
                {
                    var proxyRequest = ProxyRequestBuilder <string[]>
                                       .CreateBuilder(baseUri, HttpRequestMethod.Get)
                                       .AppendToRoute("api/example")
                                       // Override the default Accept header value
                                       .Accept("application/json")
                                       .Build();

                    var proxyResponse = await proxy.InvokeAsync(proxyRequest).ConfigureAwait(false);

                    if (proxyResponse.IsSuccessfulStatusCode)
                    {
                        // Let's see what the accept header looks like
                        var requestHeaders = proxyResponse.RequestHeaders;
                        var acceptHeader   = requestHeaders.Accept;

                        Console.WriteLine("The Overriden Accept Header Value:");
                        Console.WriteLine($"\t{acceptHeader}");

                        Console.WriteLine();

                        // Show the API response
                        var valuesArray = proxyResponse.ResponseDto;
                        Writer.WriteValues(valuesArray);
                    }
                }

                #endregion

                Console.WriteLine("\n==========\n");

                #region Injecting Delegating Handlers

                /*
                 * Another incredibly awesome thing we can do is inject a DelegatingHandler into the
                 * request pipeline of the Proxy. A DelegatingHandler sits between your request and
                 * the actual request out to the RESTful service. Think of it like a translator where
                 * you can give the translator a message, they can manipulate the message and send it
                 * to someone else. One really awesome thing you can do with Delegating Handlers is
                 * insert logging into your request pipeline!
                 *
                 * Note: The order of which you inject your Delegating Handlers matters. It is a
                 * First In First Out order (i.e. the first registered DelegatingHandler will execute first).
                 */

                proxyConfiguration = ProxyConfigurationBuilder
                                     .CreateBuilder()
                                     // Inject our LoggingDelegatingHandler
                                     .AddDelegatingHandlers(new LoggingDelegatingHandler())
                                     .UseDefaultAcceptHeader(new MediaTypeWithQualityHeaderValue("application/json"))
                                     .Build();

                using (var proxy = new Proxy(proxyConfiguration))
                {
                    var proxyRequest = ProxyRequestBuilder <string[]>
                                       .CreateBuilder(baseUri, HttpRequestMethod.Get)
                                       .AppendToRoute("api/example")
                                       .Build();

                    var proxyResponse = await proxy.InvokeAsync(proxyRequest).ConfigureAwait(false);

                    if (proxyResponse.IsSuccessfulStatusCode)
                    {
                        var valuesArray = proxyResponse.ResponseDto;
                        Writer.WriteValues(valuesArray);
                    }
                }

                #endregion

                Console.WriteLine("\n==========\n");

                #region Using Delegating Actions

                /*
                 * Even cooler than Delegating Handlers are Delegating Actions. RestWell allows for
                 * you to specify an Action Delegate to be injected into the request pipeline. This
                 * allows you to inject logic into the request pipeline without having to extend
                 * and override the DelegatingHandler class yourself.
                 *
                 * Note: You can even mix and match Delegating Handlers and Delegating Actions.
                 * Just remember, though, they are injected in FIFO order.
                 */

                proxyConfiguration = ProxyConfigurationBuilder
                                     .CreateBuilder()
                                     // Inject our Delegating Actions
                                     .AddDelegatingAction((request, _) =>
                {
                    Console.WriteLine($"Delegating Action Picked Up Request:");
                    Console.WriteLine($"\tRequest Method: {request.Method.Method}");
                    Console.WriteLine($"\tAccept Header: {request.Headers.Accept}");
                    Console.WriteLine($"\tRequest URI: {request.RequestUri}");
                    Console.WriteLine();
                }
                                                          )
                                     .UseDefaultAcceptHeader(new MediaTypeWithQualityHeaderValue("application/json"))
                                     .Build();

                using (var proxy = new Proxy(proxyConfiguration))
                {
                    var proxyRequest = ProxyRequestBuilder <string[]>
                                       .CreateBuilder(baseUri, HttpRequestMethod.Get)
                                       .AppendToRoute("api/example")
                                       .Build();

                    var proxyResponse = await proxy.InvokeAsync(proxyRequest).ConfigureAwait(false);

                    if (proxyResponse.IsSuccessfulStatusCode)
                    {
                        var valuesArray = proxyResponse.ResponseDto;
                        Writer.WriteValues(valuesArray);
                    }
                }

                #endregion
            }

            Console.ReadKey();
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            /*
             * There are two ways in which you can create a request.
             *  1. Using the ProxyRequestBuilder class (easiest)
             *  2. Implementing the IProxyRequest<TRequestDto, TResponseDto> yourself (most configurable)
             *  3. Why not both?
             */

            #region Using the Proxy Request Builder

            var proxyRequest = ProxyRequestBuilder <ExampleRequestDto, ExampleResponseDto>
                               .CreateBuilder("https://www.this.is/a/base/url/api", HttpRequestMethod.Get)
                               .AppendToRoute($"controller")
                               .Authorization("Basic", "Username:Password")
                               .Accept("application/json")
                               .AddHeader("x-customHeader", "value1", "value2", "value3")
                               .AddPathArguments("arg1", "arg2")
                               .AddQueryParameter("queryParam1", "value")
                               .SetRequestDto(new ExampleRequestDto {
                Message = "Hello World"
            })
                               .Build();

            Writer.WriteRequest(proxyRequest);

            #endregion

            Console.WriteLine("\n==========\n");

            #region Implmenting your own IProxyRequest<TRequestDto, TResponseDto>

            /*
             * Implementing the IProxyRequest<TRequestDto, TResponseDto> gives you complete control over
             * structure of the request. It also allows you to perform logic to build up your request
             * in a class of it's own rather than using the fluent ProxyRequestBuilder.
             */

            // MyProxyRequest is a custom class which implement IProxyRequest<ExampleRequestDto, ExampleResponseDto>
            // It's implementation matches the ProxyRequestBuilder code above.
            var myProxyRequest = new MyProxyRequest("https://www.this.is/a/base/url/api", new ExampleRequestDto {
                Message = "Hello World"
            });
            Writer.WriteRequest(myProxyRequest);

            #endregion

            Console.WriteLine("\n==========\n");

            #region Why Not Both?

            /*
             * There's nothing that says we can't use both methods of creaing
             * a ProxyRequest... :)
             */

            var myMixedProxyRequest = new WhyNotBothProxyRequest("https://www.this.is/a/base/url/api", new ExampleRequestDto {
                Message = "Hello World"
            });
            Writer.WriteRequest(myMixedProxyRequest);

            #endregion

            Console.ReadKey();
        }
Exemplo n.º 7
0
        private static async Task MainAsync(string[] args)
        {
            using (var environment = ExampleEnvironment.Start())
            {
                /*
                 * The using statment and this line only serve the purpose of spinning up
                 * a demo API (found in RestWell.Examples.Resource.Api) that we can use for
                 * demo purposes and get it's base URI. These steps are not required for
                 * the usage of RestWell.
                 */
                var baseUri = environment.GetResourceWebService <Resource.Api.Startup>().BaseUri;

                #region Creating a ProxyRequest using the ProxyRequestBuilder

                /*
                 * First, we create a ProxyRequest using the ProxyRequestBuilder to setup a RESTful request to our demo API.
                 * Now, the request we are going to create will be a GET request with no request body. The request body
                 * returned from the API is a string array of values which should be { "value1", "value2" }.
                 */

                /*
                 * In order to have a valid request, we must specify a base URI and request type
                 * We also specify the TResposneDto as string[] since the response body is
                 * a string array.
                 */
                var proxyRequestBuilder = ProxyRequestBuilder <string[]> .CreateBuilder(baseUri, HttpRequestMethod.Get);

                // Now we add /api/example to the URI to point to the API's ExampleController
                proxyRequestBuilder.AppendToRoute("api/example");

                // Now we set the Accept header to application/json
                proxyRequestBuilder.Accept("application/json");

                /*
                 * Now that we have a ProxyRequestBuilder configured for our request
                 * we can use the Build() method to build a ProxyRequest
                 */
                var proxyRequest = proxyRequestBuilder.Build();

                #endregion

                #region Creating a Proxy, invoking the ProxyRequest, and obtaining a ProxyResult

                /*
                 * Now with a proxy request, we can create a proxy which we
                 * use to invoke the request. The Proxy class is disposable
                 * so we wrap it in a using statement here; however, we
                 * will cover Dependency Injection in a more advanced example.
                 */
                using (var proxy = new Proxy())
                {
                    #region Issue the ProxyRequest

                    // Use the proxy to invoke the request and obtain a response
                    var proxyResponse = await proxy.InvokeAsync(proxyRequest).ConfigureAwait(false);

                    #endregion

                    #region Use the ProxyResponse

                    // Now we see if the request was successful
                    if (proxyResponse.IsSuccessfulStatusCode)
                    {
                        // If so, we can get the response body and do something with it
                        var valuesArray = proxyResponse.ResponseDto;
                        Writer.WriteValues(valuesArray);
                    }

                    // Otherwise, we should probably handle a failed request
                    else
                    {
                        Console.WriteLine("The request failed!!! :(");
                    }

                    #endregion
                }

                #endregion
            }

            Console.ReadKey();
        }