要使用AspNet Core WebAPI和UWP进行通信,可以按照以下步骤操作:
创建AspNet Core WebAPI项目:
在控制器类中添加一些API方法:
using Microsoft.AspNetCore.Mvc;
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public ActionResult> Get()
{
return new string[] { "value1", "value2" };
}
[HttpGet("{id}")]
public ActionResult Get(int id)
{
return "value";
}
[HttpPost]
public void Post([FromBody] string value)
{
}
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
启动AspNet Core WebAPI项目:
创建UWP项目:
在UWP项目中添加HttpClient以与WebAPI进行通信:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace UWPApp
{
public sealed partial class MainPage : Page
{
private HttpClient httpClient;
public MainPage()
{
this.InitializeComponent();
httpClient = new HttpClient();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
Uri requestUri = new Uri("http://localhost:port/api/values");
HttpResponseMessage response = await httpClient.GetAsync(requestUri);
string responseContent = await response.Content.ReadAsStringAsync();
// 处理响应内容
}
}
}
在UWP项目的MainPage.xaml中添加一个按钮,并在Click事件中调用API方法:
启动UWP应用程序:
请记得将代码中的"port"替换为AspNet Core WebAPI项目运行时使用的端口号。另外,还可以根据需要添加其他API方法和UWP界面元素。