我可以使用dotnet core创建uwp应用程序吗?例如,使用仅在核心中可用的httpclientfactory?

时间:2019-08-16 06:26:19

标签: c# .net-core uwp

我正在构建一个uwp应用,该应用将对服务进行呼叫以获取一些数据。我想使用dotnet核心提供的HttpClientFactory。是否可以在与uwp one相同的项目中执行此操作? 谢谢

1 个答案:

答案 0 :(得分:1)

  

我正在构建一个uwp应用,该应用将对服务进行呼叫以获取一些数据。

正如MindSwipe所说,当前我们无法在UWP中使用HttpClientFactory,如果您想使用静态API访问服务,请使用HttpClient

例如:

Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

//Add a user-agent header to the GET request. 
var headers = httpClient.DefaultRequestHeaders;

//The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
//especially if the header value is coming from user input.
string header = "ie";
if (!headers.UserAgent.TryParseAdd(header))
{
    throw new Exception("Invalid header value: " + header);
}

header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
if (!headers.UserAgent.TryParseAdd(header))
{
    throw new Exception("Invalid header value: " + header);
}

Uri requestUri = new Uri("http://www.contoso.com");

//Send the GET request asynchronously and retrieve the response as a string.
Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
string httpResponseBody = "";

try
{
    //Send the GET request
    httpResponse = await httpClient.GetAsync(requestUri);
    httpResponse.EnsureSuccessStatusCode();
    httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
    httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}