views:

242

answers:

3

So I've recd. a requirement to create an API to access our application. Not all controller actions are covered by the API (maybe 50%).

I figure I can either use the same project, check the http headers for each request and respond with either xml, JSON or html as required (much like rails).

OR

Create a new ASP.NET MVC application, deploy @ api.myapp.com and use it exclusively for API access.

I assume I could write a base controller for the first option to handle 99% of the work. The issue with the first option is we don't need (or want) API functionality for at least 1/2 of controller actions (and prob. never will).

In the second option I have a duplicate of some controllers, but the good news is most/all? my controller actions are only a couple lines of code. Typically:

Whatever whatever = new Whatever(....);
repository.Save(whatever);

Anyway, what do the stack overflowers think?

A: 

I think I'd put in the same project, but segregate it using separate routes.

API: http://example.com/api/widget/list
App: http://example.com/widget/list

You could then reuse as much code as possible -- push the data selection and other code into your BLL, for instance. Keeping it in the same project will make it easier to use your API code via AJAX from the client.

tvanfosson
+2  A: 

It seems that you want to create something like REST service. Please have a look at this post of Phil Haack.
Yes, I'm sure you can put it in the same project. But it will be better to separate them in some way (using areas from MvcContrib or move controllers of api and web application to separate assemblies like this done in SharpArchitecture. If your controllers duplicate a lot of code you may create generic controller like:

public class ControllerBase<T, Service> : Controller
where Service : IService<T>
{
    public Service service { get; set; }
    public ActionResult Save(int id)
    {
        var item = service.Get(id);
        if (TryUpdateModel<T>(item))
        {
            service.Save(item);
            return View("Success");
        }
        return View("Error", item);
    }
}

Hope this helps.

zihotki
A: 

I think putting the same code in 2 different projects is asking for trouble in the long run.

Put it all in the same project.

If you need some seperation between regular vs API requests you can use seperate routes.

You can then make a private function that does the action and just have the public facing one decide to render in html or JSON/XML

Sruly