一,创建空白解决方案WPF With Asp.Net WebApi
二,创建.Net5的WPF项目WpfApp
三,创建.Net5的Asp.Net WebApi项目WebApiProvidor
四,修改WebApiProvider项目与WpfApp项目
- 修改WebApiProvider项目的输出类型
- 复制WebApiProvider项目的Startup.cs、appsettings.json、Programe.cs中的Host初始化部分的代码到WpfApp中, 删除WebApiProvider中无用的代码
- WpfApp项目中App.xaml.cs
using System.Windows;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace WpfApp
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).Build().RunAsync();
}
}
}
- 添加Model与Controller到WpfApp项目中
using System;
namespace WpfApp.Models
{
public class Foo
{
public DateTime Registration { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using WebApiProvider.Controllers;
using WpfApp.Models;
namespace WpfApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class FooController: ControllerBase
{
private static readonly string[] Addresses = new[]
{
"Hubei", "Guangzhou", "Shengzhen", "Beijing", "Shandong", "Jingmen", "Wuhan", "Jingshan"
};
private readonly ILogger<WeatherForecastController> _logger;
public FooController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<Foo> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new Foo()
{
Registration = DateTime.Now.AddDays(index),
Age = rng.Next(12, 55),
Address = Addresses[rng.Next(Addresses.Length)]
})
.ToArray();
}
}
}
- 修改WpfApp项目的Project文件的
<Project Sdk="Microsoft.Net.Sdk.WindowsDesktop">
修改为<Project Sdk="Microsoft.Net.Sdk">
修改后的项目结构如下
五,运行效果如下