رادکام
Action | HTTP method | Relative URI |
---|---|---|
Get a product by ID | GET | /api/products/id |
Create a new product | POST | /api/products |
Update a product | PUT | /api/products/id |
Delete a product | DELETE | /api/products/id |
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace HttpClientSample
{
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
class Program
{
static HttpClient client = new HttpClient();
static void ShowProduct(Product product)
{
Console.WriteLine($"Name: {product.Name}\tPrice: " + $"{product.Price}\tCategory: {product.Category}");
}
static async Task<Uri>CreateProductAsync(Product product)
{
HttpResponseMessage response = await client.PostAsJsonAsync("api/products", product);
response.EnsureSuccessStatusCode();
// return URI of the created resource.
return response.Headers.Location;
}
static async Task<Product>GetProductAsync(string path)
{
Product product = null;
HttpResponseMessage response = await client.GetAsync(path);
if(response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
}
return product;
}
static async Task<Product>UpdateProductAsync(Product product)
{
HttpResponseMessage response = await client.PutAsJsonAsync($"api/products/{product.Id}", product);
response.EnsureSuccessStatusCode();
// Deserialize the updated product from the response body.
product = await response.Content.ReadAsAsync<Product>();
return product;
}
static async Task<HttpStatusCode>DeleteProductAsync(string id)
{
HttpResponseMessage response = await client.DeleteAsync($"api/products/{id}");
return response.StatusCode;
}
static void Main()
{
RunAsync().GetAwaiter().GetResult();
}
static async Task RunAsync()
{
// Update port # in the following line.
client.BaseAddress = new Uri("http://localhost:64195/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// Create a new product
Product product = new Product
{
Name = "Gizmo",
Price = 100,
Category = "Widgets"
};
var url = await CreateProductAsync(product);
Console.WriteLine($"Created at {url}");
// Get the product
product = await GetProductAsync(url.PathAndQuery);
ShowProduct(product);
// Update the product
Console.WriteLine("Updating price...");
product.Price = 80;
await UpdateProductAsync(product);
// Get the updated product
product = await GetProductAsync(url.PathAndQuery);
ShowProduct(product);
// Delete the product
var statusCode = await DeleteProductAsync(product.Id);
Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
کد نوشته شده بالا یک کد کامل سمت کلاینت است.
static async Task RunAsync()
{
// Update port # in the following line.
client.BaseAddress = new Uri("http://localhost:64195/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// Create a new product
Product product = new Product
{
Name ="Gizmo",
Price = 100,
Category = "Widgets"
};
var url = await CreateProductAync(product);
Console.WriteLine($"Created at {url}");
// Get the product
product = await GetProductAsync(url.PathAndQuery);
ShowProduct(product);
// Update the product
Console.WriteLine("Updating price...");
product.Price = 80;
await UpdateProductAsync(product);
// Get the updated product
product = await GetProductAsync(url.PathAndQuery);
ShowProduct(product);
// Delete the product
var statusCode = await DeleteProductAsync(product.Id);
Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");
}
catch (Exception e)
{ Console.WriteLine(e.Message);
}
Console.ReadLine();
}
Install-Package Microsoft.AspNet.WebApi.Client
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
کلاسی که مشاهده می کنید،منطبق با مدل داده ای است که در Web API استفاده شده
است. یک برنامه می تواند از HttpClient برای خواندن اطلاعات یک محصول از طریق
پاسخ HTTP استفاده کند. برنامه نیاز ندارد که کدی برای deserialize کردن
بنویسد.
static HttpClient client = new HttpClient();
static async Task RunAsync()
{
// Update port # in the following line.
client.BaseAddress = new Uri("http://localhost:64195/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
کد نوشته شده فوق:
static async Task<Product> GetProductAsync(string path)
{
Product product = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
}
return product;
}
متد GetAsync یک درخواست HTTP GET ارسال می کند. زمانی که کار متد تمام شد، یک
شیء از نوع HttpResponseMessage برمی گرداند که شامل پاسخ HTTP است. اگر کد
وضعیت پاسخ کد نشان دهنده موفقیت آمیز بودن کار متد باشد، بدنه پاسخ شامل قالب
JSON از اطلاعات محصول مورد نظر ما خواهد بود. متد ReadAsAsync را
فراخوانی کرده ایم تا قالب JSON را به یک نمونه از شیء محصول تبدیل کنیم. متد
ReadAsAsync به صورت آسنکرون عمل می کند، چون بدنه پاسخ ممکن است شامل حجم
زیادی از اطلاعات باشد.
var formatters = new
List<MediaTypeFormatter>()
{
new MyCustomFormatter(),
new JsonMediaTypeFormatter(),
new XmlMediaTypeFormatter()
};
resp.Content.ReadAsAsync<IEnumerable<Product>>(formatters);
static async Task<Uri> CreateProductAsync(Product product)
{
HttpResponseMessage response = await
client.PostAsJsonAsync("api/products", product);
response.EnsureSuccessStatusCode();
// return URI of the created resource.
return response.Headers.Location;
}
متد PostAsJsonAsync:
static async Task<Product> UpdateProductAsync(Product product)
{
HttpResponseMessage response = await
client.PutAsJsonAsync($"api/products/{product.Id}", product);
response.EnsureSuccessStatusCode();
// Deserialize the updated product from the response body.
product = await response.Content.ReadAsAsync<Product>();
return product;
}
متد PutAsJsonAsync مشابه یا متد PostAsJsonAsync عمل می کند، تنها تفاوتش
در این است که به جای درخواست POST درخواست PUT ارسال می کند.
static async Task<HttpStatusCode> DeleteProductAsync(string id)
{
HttpResponseMessage response = await
client.DeleteAsync($"api/products/{id}");
return response.StatusCode;
}
مشابه با GET، درخواست DELETE نیز بدون بدنه درخواست است، بدین معنی که
نیاز نیست تا فرمت XML یا JSON را برای DELETE مشخص کنیم.
منابع: br />
ASP.NET Web API
ASP.NET MVC - Web API
5,469بازدید
دیدگاه کاربران
هنوز دیدگاهی ثبت نشده است.
شما میتوانید درباره این مقاله، دیدگاه خود را ثبت کنید.