As @Thomas noted, WebGet has been long superseded with much better frameworks for creating REST APIs. If you haven't already, go and create a new .Net Core Web Api project in VS2015 / VS2017, run it, then see how it differs to the old WCF method. You'll notice that a lot less boilerplate code and decorating is required. Here's a rundown of some differences between WCF and ASP.NET Web API, and .Net Core is really just the next generation of this.
Below is a more comprehensive example of some code from a working controller class. If required, you can abstract this into an interface, but there's probably no point. Also notice the lack of [ServiceContract]
and [OperationContract]
decorations, among other things. Just specify the [Route(...)]
(optional - if the controller doesn't conform to the default route), and the method and Uri path using [HttpGet(...)]
, etc.
This code also assumes a few things such as dependencies being registered with the DI container (ILogger
and ICustomerRepository
). Note that .Net Core has dependency injection built in, which is a nice feature (Quick rundown).
Finally, I also recommend using Swagger if you are not already. I'm late to the party on this one but have been using it lately and it is a boon for API development (the extensive commenting below assists in making Swagger more useful):
[Route("api/[controller]")]
public class CustomersController : Controller
{
ILogger<CustomersController> log;
ICustomerRepository customerRepository;
public CustomersController(ILogger<CustomersController> log, ICustomerRepository customerRepository)
{
this.log = log;
this.customerRepository = customerRepository;
}
/// <summary>
/// Get a specific customer
/// </summary>
/// <param name="customerId">The id of the Customer to get</param>
/// <returns>A customer with id matching the customerId param</returns>
/// <response code="200">Returns the customer </response>
/// <response code="404">If a customer could not be found that matches the provided id</response>
[HttpGet("{customerId:int}")]
[ProducesResponseType(typeof(ApiResult<Customer>), 200)]
[ProducesResponseType(typeof(ApiResult), 404)]
public async Task<IActionResult> GetCustomer([FromRoute] int customerId)
{
try
{
return Ok(new ApiResult<Customer>(await customerRepository.GetCustomerAsync(customerId)));
}
catch (ResourceNotFoundException)
{
return NotFound(new ApiResult($"No record found matching id {customerId}"));
}
}
}