2014年8月4日 星期一

Q&A : 使用HttpClient呼叫ASP.NET Web API

如何使用HttpClient呼叫ASP.NET Web API?

若有一個ASP.NET Web API程式如下:

public class EmployeesController : ApiController {
  static List<string> employees = new
  List<string> { "Mary" , "Candy" , "Lilly" , "Betty" , "Jessica" };
  public IEnumerable<string> Get( ) {
    return employees;
  }
  public string Get( int id ) {
    return employees[ id ];
  }
  public void Post( [FromBody]string value ) {
    employees.Add( value );
  }
  public void Put( int id , [FromBody]string value ) {
    employees[ id ] = value;
  }
  public void Delete( int id ) {
    employees.RemoveAt( id );
  }
}


我們可以使用HttpClient來進行呼叫,以下範例在Console 程式呼叫Get:



static async void Gettest( ) {
  HttpClient client = new HttpClient( );
  client.BaseAddress = new Uri( "http://localhost:25201/" );
  HttpResponseMessage resp = client.GetAsync( "api/employees" ).Result;
  IEnumerable<string> data = null;
  if ( resp.IsSuccessStatusCode ) {
    data = resp.Content.ReadAsAsync<IEnumerable<string>>( ).Result;
    foreach ( var item in data ) {
      Console.WriteLine( item);
    }
  }
}

POST,新增一筆


static async void posttest( ) {
  var client = new HttpClient( );
  client.BaseAddress = new Uri( @"http://localhost:25201/" );
  var response = await client.PostAsJsonAsync( "api/employees" , "hahaha" );
  if ( response.IsSuccessStatusCode ) {
    Console.WriteLine( "Inserted");
  }
}



PUT,修改第一筆


static async void puttest( ) {
  var client = new HttpClient( );
  client.BaseAddress = new Uri( @"http://localhost:25201/" );     
  var response = await client.PutAsJsonAsync( "api/employees/0" , "new xxx" );
  if ( response.IsSuccessStatusCode ) {
    Console.WriteLine( "updated" );
  }
}
DELETE第一筆


static async void deletetest( ) {
  var client = new HttpClient( );
  client.BaseAddress = new Uri( @"http://localhost:25201/" );
  var response = await client.DeleteAsync( "api/employees/0" );
  if ( response.IsSuccessStatusCode ) {
    Console.WriteLine( "deleted" );
  }
}

沒有留言:

總網頁瀏覽量