Пример #1
0
        public async Task <ActionResult> Edit(int id, [Bind("Id,Title,Owner")] Todo todo)
        {
            await _downstreamWebApi.CallWebApiForUserAsync <Todo, Todo>(
                ServiceName,
                todo,
                downstreamWebApiOptionsOverride : options =>
            {
                options.HttpMethod   = HttpMethod.Patch;
                options.RelativePath = $"api/todolist/{todo.Id}";
            });

            return(RedirectToAction("Index"));
        }
        public override async Task <HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            var httpContext = context.GetHttpContext();

            httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);
            using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                // Do something with apiResult
            }
            else
            {
                var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
            }

            return(new HelloReply()
            {
                Message = "Hello " + request.Name
            });
        }
        /// <summary>
        /// Calls the web API with an HttpPost, providing strongly typed input and getting
        /// strongly typed output.
        /// </summary>
        /// <typeparam name="TOutput">Output type.</typeparam>
        /// <typeparam name="TInput">Input type.</typeparam>
        /// <param name="downstreamWebApi">The downstream web API.</param>
        /// <param name="serviceName">Name of the service describing the downstream web API. There can
        /// be several configuration named sections mapped to a <see cref="DownstreamWebApiOptions"/>,
        /// each for one downstream web API. You can pass-in null, but in that case <paramref name="downstreamWebApiOptionsOverride"/>
        /// needs to be set.</param>
        /// <param name="relativePath">Path to the API endpoint relative to the base URL specified in the configuration.</param>
        /// <param name="inputData">Input data sent to the API.</param>
        /// <param name="downstreamWebApiOptionsOverride">Overrides the options proposed in the configuration described
        /// by <paramref name="serviceName"/>.</param>
        /// <param name="user">[Optional] Claims representing a user. This is useful in platforms like Blazor
        /// or Azure Signal R, where the HttpContext is not available. In other platforms, the library
        /// will find the user from the HttpContext.</param>
        /// <param name="authenticationScheme">Authentication scheme. If null, will use OpenIdConnectDefault.AuthenticationScheme
        /// if called from a web app, and JwtBearerDefault.AuthenticationScheme if called from a web API.</param>
        /// <returns>A strongly typed response from the web API.</returns>
        public static async Task <TOutput?> PostForUserAsync <TOutput, TInput>(
            this IDownstreamWebApi downstreamWebApi,
            string serviceName,
            string relativePath,
            TInput inputData,
            Action <DownstreamWebApiOptions>?downstreamWebApiOptionsOverride = null,
            ClaimsPrincipal?user        = null,
            string?authenticationScheme = null)
            where TOutput : class
        {
            if (downstreamWebApi is null)
            {
                throw new ArgumentNullException(nameof(downstreamWebApi));
            }

            using StringContent? input = ConvertFromInput(inputData);

            HttpResponseMessage response = await downstreamWebApi.CallWebApiForUserAsync(
                serviceName,
                authenticationScheme,
                PrepareOptions(relativePath, downstreamWebApiOptionsOverride, HttpMethod.Post),
                user,
                input).ConfigureAwait(false);

            return(await ConvertToOutput <TOutput>(response).ConfigureAwait(false));
        }
    public async Task <IEnumerable <WeatherForecast> > Get()
    {
        using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false);

        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            // Do something
        }
        else
        {
            var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
        }

        return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
               .ToArray());
    }
Пример #5
0
        public async Task <IEnumerable <WeatherForecast> > Get()
        {
            HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);

            var response = await _downstreamWebApi.CallWebApiForUserAsync("CalledApi").ConfigureAwait(false);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                // Do something
            }
            else
            {
                string error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
            }

            var rng = new Random();

            return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
                   .ToArray());
        }
        public async Task <ActionResult> CallAzureFunction()
        {
            string message = await _downstreamWebApi.CallWebApiForUserAsync <string>(
                "AzureFunction");

            ViewBag.reply = message;
            return(View());
        }
 public async Task OnGet()
 {
     //https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-web-app-call-api-call-api?tabs=aspnetcore
     OrdersList = await _integrationWebApi.CallWebApiForUserAsync <Order[]>("OrdersViaOnBehalfOf", options =>
     {
         options.RelativePath = "OrdersOnBehalfOf";
     });
 }
Пример #8
0
        public async Task <ActionResult> Get()
        {
            _logger.LogInformation("Trying to call a downstream Api");
            var value = await _downstreamWebApi.CallWebApiForUserAsync(
                "WebApi2",
                options =>
            {
                options.HttpMethod   = HttpMethod.Get;
                options.RelativePath = "api/downstream";
            });

            return(Ok(value));
        }
Пример #9
0
        // GET: TodoList
        public async Task <ActionResult> Index()
        {
            var value = await _downstreamWebApi.CallWebApiForUserAsync <object, IEnumerable <Todo> >(
                ServiceName,
                null,
                options =>
            {
                options.RelativePath = "api/todolist";
            });

            return(View(value));
        }
Пример #10
0
        public async Task <string> Get()
        {
            using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(await response.Content.ReadAsStringAsync().ConfigureAwait(false));

                // Do something
            }
            else
            {
                var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
            }
        }
Пример #11
0
        public async Task OnGet()
        {
            using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ViewData["ApiResult"] = apiResult;
            }
            else
            {
                var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
            }
        }
Пример #12
0
        /// <summary>
        /// Call a web API endpoint with an HttpGet,
        /// and return strongly typed data.
        /// </summary>
        /// <typeparam name="TOutput">Output type.</typeparam>
        /// <param name="downstreamWebApi">The downstream web API.</param>
        /// <param name="serviceName">Name of the service describing the downstream web API. There can
        /// be several configuration named sections mapped to a <see cref="DownstreamWebApiOptions"/>,
        /// each for one downstream web API. You can pass-in null, but in that case <paramref name="downstreamWebApiOptionsOverride"/>
        /// needs to be set.</param>
        /// <param name="downstreamWebApiOptionsOverride">Overrides the options proposed in the configuration described
        /// by <paramref name="serviceName"/>.</param>
        /// <param name="user">[Optional] Claims representing a user. This is useful in platforms like Blazor
        /// or Azure Signal R, where the HttpContext is not available. In other platforms, the library
        /// will find the user from the HttpContext.</param>
        /// <returns>The value returned by the downstream web API.</returns>
        public static async Task <TOutput?> CallWebApiForUserAsync <TOutput>(
            this IDownstreamWebApi downstreamWebApi,
            string serviceName,
            Action <DownstreamWebApiOptions>?downstreamWebApiOptionsOverride = null,
            ClaimsPrincipal?user = null)
            where TOutput : class
        {
            if (downstreamWebApi is null)
            {
                throw new ArgumentNullException(nameof(downstreamWebApi));
            }

            HttpResponseMessage response = await downstreamWebApi.CallWebApiForUserAsync(
                serviceName,
                downstreamWebApiOptionsOverride,
                user,
                null).ConfigureAwait(false);

            return(await ConvertToOutput <TOutput>(response).ConfigureAwait(false));
        }
        public async Task OnGet()
        {
            var user = await _graphServiceClient.Me.Request().GetAsync();

            try
            {
                using (var photoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync())
                {
                    byte[] photoByte = ((MemoryStream)photoStream).ToArray();
                    ViewData["photo"] = Convert.ToBase64String(photoByte);
                }
                ViewData["name"] = user.DisplayName;

                var graphData = await _downstreamWebApi.CallWebApiForUserAsync("GraphBeta");
            }
            catch (Exception)
            {
                ViewData["photo"] = null;
            }
        }
Пример #14
0
        /// <summary>
        /// Call a web API with a strongly typed input, with an HttpGet.
        /// </summary>
        /// <typeparam name="TInput">Input type.</typeparam>
        /// <param name="downstreamWebApi">The downstream web API.</param>
        /// <param name="serviceName">Name of the service describing the downstream web API. There can
        /// be several configuration named sections mapped to a <see cref="DownstreamWebApiOptions"/>,
        /// each for one downstream web API. You can pass-in null, but in that case <paramref name="downstreamWebApiOptionsOverride"/>
        /// needs to be set.</param>
        /// <param name="inputData">Input data.</param>
        /// <param name="downstreamWebApiOptionsOverride">Overrides the options proposed in the configuration described
        /// by <paramref name="serviceName"/>.</param>
        /// <param name="user">[Optional] Claims representing a user. This is useful in platforms like Blazor
        /// or Azure Signal R, where the HttpContext is not available. In other platforms, the library
        /// will find the user from the HttpContext.</param>
        /// <returns>The value returned by the downstream web API.</returns>
        public static async Task GetForUserAsync <TInput>(
            this IDownstreamWebApi downstreamWebApi,
            string serviceName,
            TInput inputData,
            Action <DownstreamWebApiOptions>?downstreamWebApiOptionsOverride = null,
            ClaimsPrincipal?user = null)
        {
            if (downstreamWebApi is null)
            {
                throw new ArgumentNullException(nameof(downstreamWebApi));
            }

            using StringContent? input = ConvertFromInput(inputData);

            await downstreamWebApi.CallWebApiForUserAsync(
                serviceName,
                downstreamWebApiOptionsOverride,
                user,
                input).ConfigureAwait(false);
        }
Пример #15
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");

            var(authenticationStatus, authenticationResponse) =
                await req.HttpContext.AuthenticateAzureFunctionAsync();

            if (!authenticationStatus)
            {
                return(authenticationResponse);
            }

            using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                // Do something with apiResult
            }
            else
            {
                var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
            }

            string name = req.HttpContext.User.Identity.IsAuthenticated ? req.HttpContext.User.GetDisplayName() : null;

            var user = await _graphServiceClient.Me.Request().GetAsync();

            string responseMessage = string.IsNullOrEmpty(user.DisplayName)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, Graph user: {user.DisplayName}. Hello, {name} .This HTTP triggered function executed successfully.";

            return(new JsonResult(responseMessage));
        }
        /// <summary>
        /// Calls the web API endpoint with an HttpPut, providing strongly typed input data.
        /// </summary>
        /// <typeparam name="TInput">Input type.</typeparam>
        /// <param name="downstreamWebApi">The downstream web API.</param>
        /// <param name="serviceName">Name of the service describing the downstream web API. There can
        /// be several configuration named sections mapped to a <see cref="DownstreamWebApiOptions"/>,
        /// each for one downstream web API. You can pass-in null, but in that case <paramref name="downstreamWebApiOptionsOverride"/>
        /// needs to be set.</param>
        /// <param name="relativePath">Path to the API endpoint relative to the base URL specified in the configuration.</param>
        /// <param name="inputData">Input data sent to the API.</param>
        /// <param name="downstreamWebApiOptionsOverride">Overrides the options proposed in the configuration described
        /// by <paramref name="serviceName"/>.</param>
        /// <param name="user">[Optional] Claims representing a user. This is useful in platforms like Blazor
        /// or Azure Signal R, where the HttpContext is not available. In other platforms, the library
        /// will find the user from the HttpContext.</param>
        /// <param name="authenticationScheme">Authentication scheme. If null, will use OpenIdConnectDefault.AuthenticationScheme
        /// if called from a web app, and JwtBearerDefault.AuthenticationScheme if called from a web API.</param>
        /// <returns>The value returned by the downstream web API.</returns>
        public static async Task PutForUserAsync <TInput>(
            this IDownstreamWebApi downstreamWebApi,
            string serviceName,
            string relativePath,
            TInput inputData,
            Action <DownstreamWebApiOptions>?downstreamWebApiOptionsOverride = null,
            ClaimsPrincipal?user        = null,
            string?authenticationScheme = null)
        {
            if (downstreamWebApi is null)
            {
                throw new ArgumentNullException(nameof(downstreamWebApi));
            }

            using StringContent? input = ConvertFromInput(inputData);

            await downstreamWebApi.CallWebApiForUserAsync(
                serviceName,
                authenticationScheme,
                PrepareOptions(relativePath, downstreamWebApiOptionsOverride, HttpMethod.Put),
                user,
                input).ConfigureAwait(false);
        }
Пример #17
0
 public async Task <HttpResponseMessage> CallDownstreamWebApiAsync()
 {
     HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);
     return(await _downstreamWebApi.CallWebApiForUserAsync(TestConstants.SectionNameCalledApi));
 }
Пример #18
0
 public Task <IEnumerable <Order> > List()
 {
     return(_downstreamWebApi.CallWebApiForUserAsync <IEnumerable <Order> >("BackEndApi", options => options.RelativePath = "Orders"));
 }
 public async Task <HttpResponseMessage> CallDownstreamWebApiAsync()
 {
     return(await _downstreamWebApi.CallWebApiForUserAsync(TestConstants.SectionNameCalledApi));
 }
Пример #20
0
 public async Task <HttpResponseMessage> CallDownstreamWebApiAsync()
 {
     return(await _downstreamWebApi.CallWebApiForUserAsync(
                TestConstants.SectionNameCalledApi,
                authenticationScheme : TestConstants.CustomJwtScheme2));
 }