DependencyInjectionExtensions - add token header - call API - Code c# gọi API post qua hệ thống khác

 









Code c# gọi API post qua hệ thống khác

using FluentValidation;
using Infrastructure.Core.Models;
using Newtonsoft.Json;
using NonSaleAggregation.Application.Infrastructure;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NonSaleAggregation.Application.Account.Commands
{
    /// <summary>
    /// test network
    /// </summary>
    public class DemoGetCLPhysicalError
    {
        public class Command : IRequestWrapper<string>
        {
            public string ObjContract { get; set; }
        }

        public class CommandValidator : AbstractValidator<Command>
        {
            public CommandValidator()
            {
                //RuleFor(x => x.Val).NotEmpty().WithMessage("Vui lòng không bỏ trống.");
            }
        }

        public class Handler : IRequestHandlerWrapper<Command, string>
        {
            private readonly HttpClient _httpClient;
            private readonly IHttpClientFactory _httpClientFactory;
            public Handler(HttpClient httpClient, IHttpClientFactory httpClientFactory)
            {
                _httpClient = httpClient;
                _httpClientFactory = httpClientFactory;
            }

            public async Task<ResultObject<string>> Handle(Command request, CancellationToken cancellationToken)
            {
                object objRequest;
                objRequest = new
                {
                    Contract = request.ObjContract
                };

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Token", "967044DB85F1AA32D8F66A0E80C00642");                

                var values = new Dictionary<string, string>
                {
                    {"Contract", "SGAAS0904"}
                };
               
                var content = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "application/json");

                var uri = new Uri(@"http://systemapi.fpt.vn/api/CLPhysicalErr/CLPhysicalError");

                var response = await client.PostAsync(uri, content);
                var responseString = await response.Content.ReadAsStringAsync();

                return await ResultObject.OkAsync<string>(responseString);

            }
        }
    }
}











Nhận xét