How to: Extend Web API Controller
This article is relevant to entity models that utilize the deprecated Visual Studio integration of Telerik Data Access. The current documentation of the Data Access framework is available here.
This topic describes how to extend the generated Web API controllers with custom action methods.
Using Partial Classes
When working with automatically generated source (like the controllers generated by the Service Wizard), code can be added to the class without having to modify the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code and so on. You can create code that uses these classes without having to edit the file created by Visual Studio. Using partial classes is a perfect solution for separating auto-generated code from developer code. The most compelling reason for using partial class is to separate your application business logic from the designer-generated code.
Do not modify the original source files generated by the Service Wizard. If you re-generate your controllers later, all changes will be lost. Instead, add your custom methods in a partial class.
Suppose, you have a controller named CarsController.
Basically, what you need to do is:
-
Create a new class with the same name as the name of the controller you want to extend. Use the following naming pattern: <ControllerName>.partial.cs for C# or <ControllerName>.partial.vb for VB.
The new partial class should be in the same namespace as the original.
- Mark the class with the partial keyword.
- Add your custom action methods.
For example, the GetCarByMakeModel method returns a single car by its make and model.
using System.Net;
using System.Web.Http;
namespace WebApplication
{
public partial class CarsController
{
public virtual Car GetCarByMakeModel( string make, string model )
{
Car entity = repository.GetBy( c => c.Make == make && c.Model == model );
if ( entity == null )
{
throw new HttpResponseException( HttpStatusCode.NotFound );
}
return entity;
}
}
}
Imports System.Net
Imports System.Web.Http
Namespace WebApplication1
Partial Public Class CarsController
Public Overridable Function GetCarByMakeModel(ByVal make As String, ByVal model As String) As Car
Dim entity As Car = repository.GetBy(Function(c) c.Make = make AndAlso c.Model = model)
If entity Is Nothing Then
Throw New HttpResponseException(HttpStatusCode.NotFound)
End If
Return entity
End Function
End Class
End Namespace