コード例 #1
0
ファイル: APIServices.cs プロジェクト: et-enchill/LunchApp
        public async Task <ResponseData <TModel> > PostAsync <TModel>(string endPoint, object data)
        {
            try
            {
                var client = await _client.GetClientAsync();

                var request = new HttpRequestMessage(HttpMethod.Post, endPoint);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                request.Content = new StringContent(JsonConvert.SerializeObject(data));
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, _cancellationTokenSource.Token);

                var content = await response.Content.ReadAsStringAsync();

                return(new ResponseData <TModel>()
                {
                    Code = (int)response.StatusCode,
                    Status = response.IsSuccessStatusCode ? StatusSuccessful : "Fail",
                    Caption = response.ReasonPhrase.ToString(),
                    Body = response.IsSuccessStatusCode ? JsonConvert.DeserializeObject <TModel>(content) : default
                });
            }