How to make webhookcontroller active? - c#

I'm creating a chatbot in facebook messenger using dialogflow for the webhook i'm using visual studio c# .
I want to send a message to the user in chatbot messenger in a specific moment.
I have different two controller , the first one is for intent fulfillment:
namespace WebhookReceiver.Controllers
{
public class FirstController : ApiController
{
GlobalClasses gc = new GlobalClasses();
public string Get()
{
return "OK";
}
public int Get(int id)
{
return id;
}
public ApiAiResponse Post([FromBody]JObject jsonRequest)
{
using (WebhookReceiverModelDataContext ctx = new
WebhookReceiverModelDataContext())
{
ApiAiRequest request = jsonRequest.ToObject<ApiAiRequest>();
ApiAiResponse response = new ApiAiResponse();
JObject jObject = JObject.Parse(request.result.parameters.ToString());
if ("input.data".Equals(request.result.action.ToLower()))
{
speechLang = "xxxx";
source = "NoResult";
}
The second controller i have created to send broadcast message( i don't know how to call this controller when action input.data ( in firstcontroller) is called.
I'm saving PSID of the user to send broadcast message in another moment (when an event will be online) .
public HttpResponseMessage Get()
{
var querystrings = Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
if (querystrings["hub.verify_token"] == "xxxx")
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(querystrings["hub.challenge"], Encoding.UTF8, "text/plain")
};
}
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
[HttpPost]
public async Task<HttpResponseMessage> Post()
{
var signature = Request.Headers.GetValues("X-Hub-Signature").FirstOrDefault().Replace("sha1=", "");
var body = await Request.Content.ReadAsStringAsync();
if (!VerifySignature(signature, body))
return new HttpResponseMessage(HttpStatusCode.BadRequest);
var value = JsonConvert.DeserializeObject<WebhookModel>(body);
if (value._object != "page")
return new HttpResponseMessage(HttpStatusCode.OK);
foreach (var item in value.entry[0].messaging)
{
if (item.message == null && item.postback == null)
continue;
else
await SendMessage(GetMessageTemplate(item.message.text, item.sender.id));
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
private bool VerifySignature(string signature, string body)
{
var hashString = new StringBuilder();
using (var crypto = new HMACSHA1(Encoding.UTF8.GetBytes(appSecret)))
{
var hash = crypto.ComputeHash(Encoding.UTF8.GetBytes(body));
foreach (var item in hash)
hashString.Append(item.ToString("X2"));
}
return hashString.ToString().ToLower() == signature.ToLower();
}
/// <summary>
/// get text message template
/// </summary>
/// <param name="text">text</param>
/// <param name="sender">sender id</param>
/// <returns>json</returns>
private JObject GetMessageTemplate(string text, string sender)
{
return JObject.FromObject(new
{
recipient = new { id = sender },
message = new { text = text }
});
}
/// <summary>
/// send message
/// </summary>
/// <param name="json">json</param>
private async Task SendMessage(JObject json)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage res = await client.PostAsync($"https://graph.facebook.com/v2.6/me/messages?access_token={pageToken}", new StringContent(json.ToString(), Encoding.UTF8, "application/json"));
}
}
Have you any idea how to send notification message using this webhook for users who are subscribed in the bot ?
I want to get the timer from the database . The schema database will be like this :
ID | Message | Event | EventDate | 1 | text text | Birthday | 13/04/2018 17:05

Related

.NET 7 MAUI not receiving http response

I am playing around with .NET MAUI, and I got a problem. I call a rest API endpoint, and it is called, no errors (works 100% because I got response in Postman and on the SwaggerUI). But my mobile app client never receives a response. I probably miss something. Any idea is welcome.
namespace Mobile.UI.Clients;
public abstract class BaseClient
{
private readonly HttpClient httpClient;
private readonly MobileAppSettings settings;
private string BaseURL
{
get
{
return DeviceInfo.Platform == DevicePlatform.Android ?
this.settings.AndroidBaseURL :
this.settings.IosBaseURL;
}
}
protected BaseClient(HttpClient httpClient, MobileAppSettings settings)
{
this.settings = settings;
this.httpClient = BuildHttpClient(httpClient);
}
/// <summary>
/// Creates a simple get request
/// </summary>
/// <typeparam name="T">The return type</typeparam>
/// <param name="route">The route part without the base url</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
protected async Task<T> SendGetRequestAsync<T>(string route)
{
try
{
var uri = BuildUri(route);
var response = await httpClient.GetAsync(uri);
if (!response.IsSuccessStatusCode)
{
throw new Exception("Faild to fetch data.");
}
var content = await SerializeResponse<T>(response.Content);
return content;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// Creates a simple get request
/// </summary>
/// <typeparam name="T">The return type</typeparam>
/// <param name="route">The route part without the base url</param>
/// <param name="routParam">Rout parameter</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
protected async Task<T> SendGetRequestAsync<T>(string route, object routParam)
{
try
{
var uri = BuildUri(route, routParam);
var response = await httpClient.GetAsync(uri);
if (!response.IsSuccessStatusCode)
{
throw new Exception("Faild to fetch data.");
}
var content = await SerializeResponse<T>(response.Content);
return content;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private HttpClient BuildHttpClient(HttpClient httpClient)
{
#if DEBUG
var handler = new HttpsClientHandlerService();
httpClient = new HttpClient(handler.GetPlatformMessageHandler());
#endif
httpClient.BaseAddress = new Uri(BaseURL);
httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new("application/json"));
return httpClient;
}
private Uri BuildUri(string route)
{
return new Uri(Path.Combine(BaseURL, settings.ApiVersion, route));
}
private Uri BuildUri(string route, object routParam)
{
return new Uri(Path.Combine(BaseURL, settings.ApiVersion, route, $"{routParam}"));
}
private async Task<T> SerializeResponse<T>(HttpContent content)
{
var stream = await content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<T>(stream);
}
}
public class PlayerClient : BaseClient, IPlayerClient
{
public PlayerClient(HttpClient httpClient, MobileAppSettings settings) : base(httpClient, settings)
{}
public async Task<List<PlayerModel>> GetAllAsync()
{
var path = #"players/get-all";
return await SendGetRequestAsync<List<PlayerModel>>(path);
}
}
public class HttpsClientHandlerService : IHttpsClientHandlerService
{
public HttpMessageHandler GetPlatformMessageHandler()
{
#if ANDROID
var handler = new Xamarin.Android.Net.AndroidMessageHandler();
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (cert != null && cert.Issuer.Equals("CN=localhost"))
return true;
return errors == System.Net.Security.SslPolicyErrors.None;
};
return handler;
#elif IOS
var handler = new NSUrlSessionHandler
{
TrustOverrideForUrl = IsHttpsLocalhost
};
return handler;
#elif WINDOWS || MACCATALYST
return null;
#else
throw new PlatformNotSupportedException("Only Android, iOS, MacCatalyst, and Windows supported.");
#endif
}
#if IOS
public bool IsHttpsLocalhost(NSUrlSessionHandler sender, string url, Security.SecTrust trust)
{
if (url.StartsWith("https://localhost"))
return true;
return false;
}
#endif
}
In the android message handler I captured an error (if it is an error):
System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors | System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch

How to get specific data from external API in ASP.Net

I am trying to fetch the holiday data from an external API in asp.net. The fetch works, but I'd like to use it as a reference on the annual date.
cspublic string Get()
{
HttpClient http = new HttpClient();
http.DefaultRequestHeaders.Add("APIKey", "Application/Json");
var data = http.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
return data;
}
i have this code in my repository file to get external api
i want to get is_national_holiday == true
https://api-harilibur.vercel.app/api
[
{
"holiday_date": "2021-01-1",
"holiday_name": "Tahun Baru Masehi",
"is_national_holiday": true
},
{
"holiday_date": "2021-01-12",
"holiday_name": "Hari Siwa Ratri",
"is_national_holiday": false
},
{
"holiday_date": "2021-01-30",
"holiday_name": "Hari Saraswati",
"is_national_holiday": false
},
{
"holiday_date": "2021-02-12",
"holiday_name": "Tahun Baru Imlek 2572 Kongzili",
"is_national_holiday": true
}
]
Update :
Repository
public async Task<HoliDate> GetHolidaysAsync()
{
var client = new RestClient($"https://api-harilibur.vercel.app/api");
var request = new RestRequest(Method.GET);
IRestResponse response = await client.ExecuteAsync(request);
if (response.IsSuccessful)
{
var content = JsonConvert.DeserializeObject<JToken>(response.Content);
var holidayCaption = content["holiday_date"].Value<DateTime>();
var holidays = content.SelectTokens("aa")
.Select(team => new Holiday
{
holiday_date = (DateTime)team["holiday_date"],
holiday_name = (string)team["holiday_name"],
is_national_holiday = (bool)team["is_national_holiday"]
})
.ToList();
//return the model to my caller.
return new HoliDate
{
HolidayCaption = holidayCaption,
Holiday = holidays
};
}
Console.WriteLine(response.Content);
return null;
}
Controller
[Route("Holiday")]
[HttpGet]
public async Task<IActionResult> GetByIdAsync() {
var model = await repository.GetHolidaysAsync();
if (model == null)
return NotFound();
return Ok(model);
}
Model Holiday
public class HoliDate
{
public DateTime HolidayCaption { get; set; }
public IEnumerable<Holiday> Holiday { get; set; }
}
}
An unhandled exception occurred while processing the request.
ArgumentException: Accessed JArray values with invalid key value: "HolidayCaption". Int32 array index expected.
Newtonsoft.Json.Linq.JArray.get_Item(object key)
LeaveAPI.Repository.Data.LeaveDetailRepository.GetHolidaysAsync() in LeaveDetailRepository.cs
+
var holidayCaption = content["HolidayCaption"].Value();
LeaveAPI.Controllers.LeaveDetailsController.GetByIdAsync() in LeaveDetailsController.cs
+
var model = await repository.GetHolidaysAsync();
enter image description here

asp.net core web api cant send object from client side

this is server code who cath the request from client side
[HttpPost("Add")]
public async Task<IActionResult> Add([FromBody]RequestAdd person)
{
if(person != null){
return Ok("good");
}
return Ok("false");
}
this is code is client post there i add to multipart json and image bytes
public Task<HttpResponseMessage> Uploads(Person person, List<FileInfo> files)
{
try
{
var jsonToSend = JsonConvert.SerializeObject(person, Formatting.None);
var multipart = new MultipartFormDataContent();
var body = new StringContent(jsonToSend, Encoding.UTF8, "application/json");
multipart.Add(body, "JsonDetails");
foreach (var item in files)
{
var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(item.FullName));
multipart.Add(fileContent, item.FullName);
}
var client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
return client.PostAsync("Add", multipart);
}
catch
{
return null;
}
}
code where i use this method there i have error
static void Main(string[] args)
{
Method2();
Console.ReadLine();
}
static void Method2()
{
UploadMultiPart uploadMultiPart = new UploadMultiPart();
List<FileInfo> fileInfos = new List<FileInfo>()
{
new FileInfo(#"C:\asd\full-metal-jacket.png"),
new FileInfo(#"C:\asd\full-metal-jacket.png"),
new FileInfo(#"C:\asd\full-metal-jacket.png")
};
Person person = new Person
{
Name = "Adilbek",
SureName = "Ramazanov",
Position = "God",
Group = "heaven",
Phone = 123123
};
var result = loadMultiPart.Uploads(person,fileInfos).Result;
Console.WriteLine("Status is " + result.StatusCode);
}
error code is Status is UnsupportedMediaType
i dont have idea how to send to server, please help me sorry my bad english
Use the [FromForm] attribute, not [FromBody] attribute.
[HttpPost("Add")]
public async Task<IActionResult> Add([FromForm]RequestAdd person)
{
if(person != null){
return Ok("good");
}
return Ok("false");
}

Custom validator attribute works in unit test but not the WebAPI controller?

The ValidateMinMaxListCountAttribute validation attribute works in my unit test, but does not when used in WebAPI framework?
For example inside the unit test the "isValid" returns true, yet in the controller it fails. I'm guessing some kind of serialization issue?
Anyone have any ideas?
[TestCategory("ServiceTests")]
[TestMethod]
public void CallServiceCalc()
{
var client = new RestClient();
client.BaseUrl = new Uri("https://localhost:44379");
client.Authenticator = new HttpBasicAuthenticator("eric.schneider", "password");
var request = new RestRequest();
request.Resource = "api/Calculation/Calculate";
CoralRequest coralReq = new CoralRequest();
coralReq.ModelId = 1;
coralReq.ModelName = "2018";
coralReq.BasePlan = new BeneifitsPlanInputs();
coralReq.Plans.Add(new BeneifitsPlanInputs());
request.AddBody(coralReq);
ValidateMinMaxListCountAttribute va = new ValidateMinMaxListCountAttribute(1, 999);
bool isValid = va.IsValid(coralReq.Plans);
IRestResponse response = client.Execute(request);
Assert.IsTrue(response.StatusCode == System.Net.HttpStatusCode.OK, "Should not be ok");
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ValidateMinMaxListCountAttribute : ValidationAttribute
{
public ValidateMinMaxListCountAttribute(int minimum, int maximum)
{
this.MinimumCount = minimum;
this.MaximumCount = maximum;
}
public int MinimumCount { get; set; }
public int MaximumCount { get; set; }
public override bool IsValid(object value)
{
var list = value as ICollection;
if (list != null)
{
if (list.Count > MaximumCount) { return false; }
if (list.Count < MinimumCount) { return false; }
return true;
}
return false;
}
}
public class CoralRequest
{
public CoralRequest()
{
this.Plans = new List<BeneifitsPlanInputs>();
}
/// <summary>
///
/// </summary>
[ValidateMinMaxListCount(1, 99, ErrorMessage = "Must have between 1 and 99 plans")]
public IList<BeneifitsPlanInputs> Plans { get; set; }
}
Based on one of your other questions, which seems to be related, you show that the controller action looks like...
[HttpGet("{mock}")]
public ActionResult<CoralResult> CalculateMock(CoralRequest mock)
While in the test, a GET request is being made, GET requests do not have a BODY, and yet you add one to the request. Meaning that most likely the model is not being populated/bind to correctly on the server
This looks like a classic XY problem
That action should most likely be a POST request if you want to get the BODY of the request, and the action should be refactored to explicitly state where the data should be attained from.
[Route("api/[controller]")]
public class CalculationController: Controller {
//POST api/Calculation/Calculate
[HttpPost("[action]")]
public ActionResult<CoralResult> Calculate([FromBody]CoralRequest model) {
if(ModelState.IsValid) {
CoralResult result = new CoralResult();
//...do something with model and populate result.
return result;
}
return BadRequest(ModelState);
}
}
Which should now match more closely to what was being attempted in the integration test
[TestCategory("ServiceTests")]
[TestMethod]
public void CallServiceCalc() {
var client = new RestClient();
client.BaseUrl = new Uri("https://localhost:44379");
client.Authenticator = new HttpBasicAuthenticator("eric.schneider", "password");
var request = new RestRequest(Method.POST); //<-- POST request
request.Resource = "api/Calculation/Calculate";
request.AddHeader("content-type", "application/json");
CoralRequest coralReq = new CoralRequest();
coralReq.ModelId = 1;
coralReq.ModelName = "2018";
coralReq.BasePlan = new BeneifitsPlanInputs();
coralReq.Plans.Add(new BeneifitsPlanInputs());
request.AddJsonBody(coralReq); //<-- adding data as JSON to body of request
IRestResponse response = client.Execute(request);
Assert.IsTrue(response.StatusCode == System.Net.HttpStatusCode.OK, "Should be HttpStatusCode.OK");
}
The model binder should now be able to validate the model after binding it and passing it to the action.
Reference Model Binding in ASP.NET Core

PostAsync throwing IRandomAccessStream error when targeting windows 10 UWP

I'm in the process of porting my windows 8.1 app to windows 10 UWP, but calling PostAsync now throws an exception.
This exact code works perfectly when targeting 8.1, but when I target Windows 10 UWP, it throws the following exception:
This IRandomAccessStream does not support the GetInputStreamAt method because it requires cloning and this stream does not support cloning.
Code
public async void TestPost()
{
var parameters = GetParameters();
var formattedData = new FormUrlEncodedContent(parameters);
using (var clientHandler = new HttpClientHandler { Credentials = GetCredentials() })
{
using (var httpClient = new HttpClient(clientHandler))
{
var response = await httpClient.PostAsync(postUrl, formattedData);
}
}
}
private Dictionary<string, string> GetParameters()
{
var parameters = new Dictionary<string, string>();
parameters["grant_type"] = "url";
parameters["device_id"] = "unique key";
parameters["redirect_uri"] = "redirect url";
return parameters;
}
public static NetworkCredential GetCredentials()
{
return new NetworkCredential("<secret key>", "");
}
Stacktrace
at System.IO.NetFxToWinRtStreamAdapter.ThrowCloningNotSuported(String methodName)
at System.IO.NetFxToWinRtStreamAdapter.GetInputStreamAt(UInt64 position)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpHandlerToFilter.<SendAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpClientHandler.<SendAsync>d__1.MoveNext()
Have you tried using Windows.Web.Http.HttpClient instead?
// using Windows.Web.Http;
// using Windows.Web.Http.Filters;
var parameters = GetParameters();
var formattedData = new HttpFormUrlEncodedContent(parameters);
using (var clientHandler = new HttpBaseProtocolFilter())
{
clientHandler.ServerCredential = GetCredentials();
using (var httpClient = new HttpClient(clientHandler))
{
var response = await httpClient.PostAsync(postUrl, formattedData);
}
}
Its a bug. The workaround is to use Windows.Web
using Windows.Web.Http;
using Windows.Web.Http.Filters;
using Windows.Web.Http.Headers;
/// <summary>
/// Performs the post asynchronous.
/// </summary>
/// <typeparam name="T">The generic type parameter.</typeparam>
/// <param name="uri">The URI.</param>
/// <param name="objectToPost">The object to post.</param>
/// <returns>The response message.</returns>
private static async Task<HttpResponseMessage> PerformPostAsync<T>string uri, object objectToPost)
{
HttpResponseMessage response = null;
// Just add default filter (to enable enterprise authentication)
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
using (HttpClient client = HttpService.CreateHttpClient(filter))
{
// Now create the new request for the post
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(uri));
if (objectToPost != null)
{
// Frist get the bytes
byte[] bytes = UTF8Encoding.UTF8.GetBytes(JsonHelper.Serialize(objectToPost));
// Now create the HttpBufferContent from the bytes and set the request content
IHttpContent content = new HttpBufferContent(bytes.AsBuffer());
content.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(HttpService.JsonMediaType);
request.Content = content;
}
// Now complete the request
response = await client.SendRequestAsync(request);
}
return response;
}
/// <summary>
/// Creates the HTTP client.
/// </summary>
/// <param name="filter">The filter.</param>
/// <returns>HTTP client.</returns>
private static HttpClient CreateHttpClient(HttpBaseProtocolFilter filter = null)
{
HttpClient client = new HttpClient(filter);
client.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue(HttpService.JsonMediaType));
return client;
}
}
We needed to use the PCL System.Net.Http library for cross-platform so we couldn't just swap everything over to use the platform specific library. We ended up using a different HttpMessageHandler for the specific problematic cases. That handler delegates the actual call to the Windows.Web.Http library.
/// <summary>
/// A System.Net.Http message handler that delegates out to Windows.Web.Http.HttpClient.
/// </summary>
public class WindowsHttpMessageHandler : HttpMessageHandler
{
private const string UserAgentHeaderName = "User-Agent";
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();
Windows.Web.Http.HttpRequestMessage webRequest = new Windows.Web.Http.HttpRequestMessage
{
Method = ConvertMethod(request.Method),
RequestUri = request.RequestUri,
Content = await ConvertRequestContentAsync(request.Content).ConfigureAwait(false),
};
CopyHeaders(request.Headers, webRequest.Headers);
Windows.Web.Http.HttpResponseMessage webResponse = await client.SendRequestAsync(webRequest)
.AsTask(cancellationToken)
.ConfigureAwait(false);
HttpResponseMessage response = new HttpResponseMessage
{
StatusCode = ConvertStatusCode(webResponse.StatusCode),
ReasonPhrase = webResponse.ReasonPhrase,
Content = await ConvertResponseContentAsync(webResponse.Content).ConfigureAwait(false),
RequestMessage = request,
};
CopyHeaders(webResponse.Headers, response.Headers);
return response;
}
private static void CopyHeaders(HttpRequestHeaders input, Windows.Web.Http.Headers.HttpRequestHeaderCollection output)
{
foreach (var header in input)
{
output.Add(header.Key, GetHeaderValue(header.Key, header.Value));
}
}
private static void CopyHeaders(HttpContentHeaders input, Windows.Web.Http.Headers.HttpContentHeaderCollection output)
{
foreach (var header in input)
{
output.Add(header.Key, GetHeaderValue(header.Key, header.Value));
}
}
private static void CopyHeaders(Windows.Web.Http.Headers.HttpContentHeaderCollection input, HttpContentHeaders output)
{
foreach (var header in input)
{
if (!string.Equals(header.Key, "Expires", StringComparison.OrdinalIgnoreCase) || header.Value != "-1")
{
output.Add(header.Key, header.Value);
}
}
}
private static void CopyHeaders(Windows.Web.Http.Headers.HttpResponseHeaderCollection input, HttpResponseHeaders output)
{
foreach (var header in input)
{
output.Add(header.Key, header.Value);
}
}
private static string GetHeaderValue(string name, IEnumerable<string> value)
{
return string.Join(string.Equals(name, UserAgentHeaderName, StringComparison.OrdinalIgnoreCase) ? " " : ",", value);
}
private static Windows.Web.Http.HttpMethod ConvertMethod(HttpMethod method)
{
return new Windows.Web.Http.HttpMethod(method.ToString());
}
private static async Task<Windows.Web.Http.IHttpContent> ConvertRequestContentAsync(HttpContent content)
{
if (content == null)
{
return null;
}
Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false);
var result = new Windows.Web.Http.HttpStreamContent(contentStream.AsInputStream());
CopyHeaders(content.Headers, result.Headers);
return result;
}
private static async Task<HttpContent> ConvertResponseContentAsync(Windows.Web.Http.IHttpContent content)
{
var responseStream = await content.ReadAsInputStreamAsync();
var result = new StreamContent(responseStream.AsStreamForRead());
CopyHeaders(content.Headers, result.Headers);
return result;
}
private static HttpStatusCode ConvertStatusCode(Windows.Web.Http.HttpStatusCode statusCode)
{
return (HttpStatusCode)(int)statusCode;
}
}
Though since we only needed it for a couple of calls it's not 100% tested for all use cases.

Categories

Resources