Reputation:
While I have been using the Microsoft .NET Framework for some years now, I am a novice when it comes to ASP.NET, particularly the ASP.NET WebAPI Framework. I am considering using the ASP.NET WebAPI framework for a small project.
I was having a look over the ASP.NET WebAPI poster, and noticed that a Controller
class can either:
ApiController
class, orIHttpController
interfaceReading the MSDN documentation for the ApiController
class shows that it implements IHttpController
. It appears that IHttpController
simply declares a single method called ExecuteAsync()
.
What I am not clear on is: under what circumstances should you derive from ApiController
, or simply implement the IHttpController
interface's ExecuteAsync()
method? What are the pros and cons of each approach?
Upvotes: 4
Views: 2981
Reputation: 142014
If you use IHttpController
there is no action selection and no action filters. You simply get a HTTPRequestMessage
and return a HTTPResponseMessage
.
Using IHttpController is actually a very simple way of returning content if your requirements are straightforward. You can still use all the regular HttpContent objects that you would use in a regular ApiController action.
public class SimpleController : IHttpController
{
public async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
RequestMessage = controllerContext.Request,
Content = new StringContent("Hello World")
};
}
}
Upvotes: 4
Reputation: 44439
If this is the same as the base controllers in MVC: it's easiest to just derive from the baseclass (ApiController
). This provides an extra level of abstraction between you and some basic request handling, something you usually want to avoid doing yourself.
In the case of ASP.NET MVC you can create your own IController
class if you want to customize the way the framework handles requests. This includes action methods, view rendering, etc.
The Controller
(and ApiController
) class is provided by ASP.NET as a standard implementation of all these things and gives you the pre-defined ways of handling a request.
Use IHttpController
if you want to customize all these "low-level" things; use ApiController
if you have no very specific need to alter anything.
A Controller
its ExecuteAsync()
method (Execute
in MVC) will serve as the very basic entrypoint for requests. Returning data from this method as a view includes writing string to the requestContext
response; hardly a very comfortable way of working.
It allows you to define your own controllers and gives you very much room for adaptation, but it also means that you will have to reinvent a whole lot of wheels.
Upvotes: 6