Refer back to the article on how to implement CRUD operation using WebAPI. Today I am going to show you the other side of the story.
The code is surprisingly simple, let me show you one by one:
- Create
public async Task<bool>CreateAsync(Person person)
{
HttpResponseMessage response = await PostAsJsonAsync<Person>(Servic eUris.ControllerBaseAddress, person);
return response.IsSuccessStatusCode;
}
- Read all
public async Task<IEnumerable<Person>> GetAsync()
{
var response = Get(ServiceUris. ControllerBaseAddress);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<L ist<Person>>();
}
else
{
return null;
}
}
- Read one
public async Task<Person> GetAsync(int id)
{
var response = Get(UriAddress(id));
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<P erson>();
}
else
{
throw new HttpClientException(response);
}
}
- Update
public async Task<bool> UpdateAsync(Person person)
{
var putUri = UriAddress(person.Id);
Debug.WriteLine(putUri);
HttpResponseMessage response = await PutAsJsonAsync<Person>(putUri, person);
return response.IsSuccessStatusCode;
}
- Delete
public async Task DeleteAsync(int id)
{
await base.DeleteAsync(UriAddress( id));
}
The constructor of the class is looks like the following:
public PersonManager(string baseAddress)
: base(baseAddress)
{
}
I have a few unit test cases for it, let me show you some:
[TestMethod]
public void PersonManagerGetAsyncTest()
{
var target = new PersonManager(TestSettingsLoca l.ServiceBaseAddress);
var result = target.GetAsync().Result;
Assert.IsNotNull(result);
foreach (var p in result)
{
Debug.WriteLine(p.ToString());
}
}
public void PersonManagerGetAsyncByIdTest( )
{
var target = new PersonManager(TestSettingsLoca l.ServiceBaseAddress);
var result = target.GetAsync(1).Result;
Assert.AreEqual("Peter", result.FirstName);
Assert.AreEqual("Lu", result.LastName);
}
You might notice that the code here is very simple, it does not even have HTTP related code. Well the code here is simple is because there is a base class does all the heavy lifting behind the scene. This is how the class is defined.
public class MyServiceProxy : ProxyBase
{
}
For these who are interested to see how ProxyBase is written, please drop me an email, I will send you the source code for the base class.
No comments:
Post a Comment