首页 > 解决方案 > 我可以使用 dotnet core 创建一个 uwp 应用程序吗?例如并使用仅在核心中可用的 httpclientfactory?

问题描述

我正在构建一个 uwp 应用程序,它将对服务进行休息调用以获取一些数据。我想使用 dotnet core 提供的 HttpClientFactory。是否可以在与 uwp 相同的项目中执行此操作?谢谢

标签: c#.net-coreuwp

解决方案


我正在构建一个 uwp 应用程序,它将对服务进行休息调用以获取一些数据。

正如 MindSwipe 所说,目前我们无法HttpClientFactory在 UWP 中使用,如果您想使用 restful 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;
}

推荐阅读