Asp.Net Web Api搭配客户端程序的使用
本例以Winform程序为例连接Web Api获取数据:
web api代码在以链接中为例:https://blog.csdn.net/qq_43024228/article/details/108078659
客户端如下(包含四种请求:Get,Post,Put,Delete):
项目结构:
一、创建Addresses类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormClient0826
{
public class Addresses
{
//http://localhost:10346/api/Product
public const string BaseAddress = "http://localhost:10346/";
public const string ProductsApi = "api/Product";
}
}
二、首先新建Product类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormClient0826
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
三、创建ProductClient类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace WinFormClient0826
{
public class ProductClient : HttpClientHelper<Product>
{
public ProductClient(string baseAddress) : base(baseAddress) { }
public override async Task<IEnumerable<Product>> GetAllAsync(string requestUri)
{
IEnumerable<Product> products = await base.GetAllAsync(requestUri);
//Product products = await base.GetAllAsync(requestUri);
return products.OrderBy(c => c.Id);
}
public async Task<XElement> GetAllXmlAsync(string requestUri)
{
using (var client = new HttpClient())
{
client.BaseAddress = _baseAddress;
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
//HttpResponseMessage resp = await client.GetAsync(requestUri);
HttpResponseMessage resp = client.GetAsync(requestUri).Result;
//WriteLine($"status from GET {resp.StatusCode}");
resp.EnsureSuccessStatusCode();
string xml = await resp.Content.ReadAsStringAsync();
XElement chapters = XElement.Parse(xml);
return chapters;
}
}
}
}
四、创建HttpClientHelper类:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace WinFormClient0826
{
public abstract class HttpClientHelper<T> where T : class
{
protected Uri _baseAddress;
public HttpClientHelper(string baseAddress)
{
if (baseAddress == null)
throw new ArgumentNullException(nameof(baseAddress));
_baseAddress = new Uri(baseAddress);
}
//etc.
private async Task<string> GetInternalAsync(string requestUri)
{
using (var client = new HttpClient())
{
client.BaseAddress = _baseAddress;
//HttpResponseMessage resp = await client.GetAsync(requestUri);
HttpResponseMessage resp = client.GetAsync(requestUri).Result;
Console.WriteLine($"status from GET {resp.StatusCode}");
resp.EnsureSuccessStatusCode();
return await resp.Content.ReadAsStringAsync();
}
}
public async virtual Task<IEnumerable<T>> GetAllAsync(string requestUri)
{
string json = await GetInternalAsync(requestUri);
return JsonConvert.DeserializeObject<IEnumerable<T>>(json);
}
public async virtual Task<T> GetAsync(string requestUri)
{
string json = await GetInternalAsync(requestUri);
return JsonConvert.DeserializeObject<T>(json);
}
//POST
public async Task<T> PostAsync(string uri, T item)
{
using (var client = new HttpClient())
{
client.BaseAddress = _baseAddress;
string json = JsonConvert.SerializeObject(item);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
//HttpResponseMessage resp = await client.PostAsync(uri, content);
HttpResponseMessage resp = client.PostAsync(uri, content).Result;
//WriteLine($"status from POST {resp.StatusCode}");
resp.EnsureSuccessStatusCode();
//WriteLine($"added resource at {resp.Headers.Location}");
json = await resp.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
}
//PUT
public async Task PutAsync(string uri,T item)
{
using(var client = new HttpClient())
{
client.BaseAddress = _baseAddress;
string json = JsonConvert.SerializeObject(item);
HttpContent content = new StringContent(json,Encoding.UTF8, "application/json");
//HttpResponseMessage resp = await client.PutAsync(uri,content);
HttpResponseMessage resp = client.PutAsync(uri, content).Result;
resp.EnsureSuccessStatusCode();
}
}
//Delete
public async Task DeleteAsync(string uri)
{
using (var client = new HttpClient())
{
client.BaseAddress = _baseAddress;
//HttpResponseMessage resp = await client.DeleteAsync(uri);
HttpResponseMessage resp = client.DeleteAsync(uri).Result;
resp.EnsureSuccessStatusCode();
}
}
}
}
五、窗体后台代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace WinFormClient0826
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_Query_Click(object sender, EventArgs e)
{
ReadProductsAsync().Wait();
}
private async Task ReadProductsAsync()
{
listBox1.Items.Clear();
//Console.WriteLine(nameof(ReadProductsAsync));
var client = new ProductClient(Addresses.BaseAddress);
IEnumerable<Product> products = await client.GetAllAsync(Addresses.ProductsApi);
foreach (Product product in products)
{
//Console.WriteLine(product.Name);
listBox1.Items.Add(product.Id + " " + product.Name + " " + product.Category + " " + product.Price);
}
//Console.WriteLine();
}
private async Task ReadProductAsync(int index)
{
//Console.WriteLine(nameof(ReadProductAsync));
var client = new ProductClient(Addresses.BaseAddress);
//var products = await client.GetAllAsync(Addresses.ProductsApi);
//var name = products.First().Id;
Product product = await client.GetAsync(Addresses.ProductsApi + "/" + index);
//Console.WriteLine($"{product.Name} {product.Category}");
listBox2.Items.Clear();
listBox2.Items.Add(product.Id + " " + product.Name + " " + product.Category + " " + product.Price);
//Console.WriteLine();
}
private void btn_QuerySingle_Click(object sender, EventArgs e)
{
int index = Convert.ToInt32(textBox1.Text);
ReadProductAsync(index).Wait();
}
private void btn_GetXML_Click(object sender, EventArgs e)
{
ReadXmlAsync().Wait();
}
private async Task ReadXmlAsync()
{
var client = new ProductClient(Addresses.BaseAddress);
XElement products = await client.GetAllXmlAsync(Addresses.ProductsApi);
richTextBox1.Text = products.ToString();
}
private void btn_Post_Click(object sender, EventArgs e)
{
AddProductAsync().Wait();
MessageBox.Show("添加成功!");
}
private async Task AddProductAsync()
{
var client = new ProductClient(Addresses.BaseAddress);
XElement products = await client.GetAllXmlAsync(Addresses.ProductsApi);
Product product = new Product()
{
Name = tb_addName.Text,
Category = tb_addCategory.Text,
Price = Convert.ToDecimal(tb_addPrice.Text)
};
product = await client.PostAsync(Addresses.ProductsApi,product);
}
private void btn_QueryID_Click(object sender, EventArgs e)
{
if(tb_putID.Text == "")
{
MessageBox.Show("Please input ID ...");
return;
}
int index = Convert.ToInt32(tb_putID.Text);
ReadIDProductAsync(index).Wait();
}
private async Task ReadIDProductAsync(int index)
{
var client = new ProductClient(Addresses.BaseAddress);
Product product = await client.GetAsync(Addresses.ProductsApi + "/" + index);
tb_putName.Text = product.Name;
tb_putCategory.Text = product.Category;
tb_putPrice.Text = product.Price.ToString();
}
private void btn_Update_Click(object sender, EventArgs e)
{
UpdateProductAsync().Wait();
}
private async Task UpdateProductAsync()
{
var client = new ProductClient(Addresses.BaseAddress);
var products = await client.GetAllAsync(Addresses.ProductsApi);
var product = products.SingleOrDefault(c => c.Id == Convert.ToInt32(tb_putID.Text));
if(product != null)
{
product.Name = tb_putName.Text;
product.Category = tb_putCategory.Text;
product.Price = Convert.ToDecimal(tb_putPrice.Text);
await client.PutAsync(Addresses.ProductsApi + "/" + product.Id,product);
}
}
private void btn_Delete_Click(object sender, EventArgs e)
{
if(tb_deleteID.Text == "")
{
MessageBox.Show("请输入需要删除的产品ID ...");
return;
}
RemoveProductAsync().Wait();
MessageBox.Show("删除成功!");
}
private async Task RemoveProductAsync()
{
var client = new ProductClient(Addresses.BaseAddress);
var products = await client.GetAllAsync(Addresses.ProductsApi);
var product = products.SingleOrDefault(c => c.Id == Convert.ToInt32(tb_deleteID.Text));
if(product != null)
{
await client.DeleteAsync(Addresses.ProductsApi + "/" + product.Id);
}
}
}
}
代码链接:https://download.csdn.net/download/qq_43024228/12807092