我试图了解如何在UWP / UAP应用程序中使用ASP.NET Core WebAPI。我以为可以像使用WCF服务一样使用WebAPI,但是我还没有找到任何关于它的信息。
此外,我尝试安装Microsoft.AspNet.WebApi.Core,但未成功,因为它与UAP不兼容(版本= V10.0)。
我现在有点迷路了。也许有人可以给我一个提示,告诉我如何在UWP应用程序中使用WebApi。
这与使用任何API调用相同。只需使用HttpClient
该类来调用端点并处理响应,预期的行为就不会有任何区别。
假设您有一个定义如下的ASP.NET Core Web API端点:
public class StackoverflowController : Controller
{
// I wanted to exemplify async capabilities.
// You'd use async/await for getting database values, etc.
[
HttpGet,
AllowAnonymous,
Route("api/greeting")
]
public Task<GreetingResult> Greeting() =>
Task.FromResult(new GreetingResult { Message = "Hello world!" });
}
public class GreetingResult
{
public string Message { get; set; }
}
假设此主机托管在`localhost:5000'上,则可以执行以下操作:
public class Consumer
{
public async Task<string> GetGreetingAsync()
{
using (var client = new HttpClient())
{
var response =
await client.GetStringAsync("http://localhost:5000/api/greeting");
// The response object is a string that looks like this:
// "{ message: 'Hello world!' }"
}
}
}
此外,您可以将其反序列化为强类型对象use Newtonsoft.Json
。我有一个UWP应用程序在这里做这个事情的例子。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句