Krishna
Krishna

Reputation: 5664

MVC and WEB API working with same controller, can any one explian how?

Here is my Controller -

    namespace MvcApplication.Controllers
    {
      public class HomeController : Controller
      {
         public ActionResult Contact()
         {
           ViewBag.Message = "Your contact page.";
           return View();
         }
         public JsonResult GetPartNumbers()
         {
           var PartNumbers = ProductModel.LoadAllPartNumbers().ToArray();
           return Json(PartNumbers, JsonRequestBehavior.AllowGet);
         }
     }
   }

I haven't inherited from ApiController. Still it's working as it can return ActionResult data types for MVC requests as well as basic data types for api requests. Here is my WebApiConfig file -

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

I am using MVC4. Now the main question is how come this working as i have not inherited from ApiController, and then what is the need of ApiController if this can work?

EDIT

public bool SaveEvent(string PartNumber, string DateTimeScheduled, string DateTimeEnd, string Notes, string PSI)
    {
        return DiaryEvent.CreateNewEvent(PartNumber, DateTimeScheduled, DateTimeEnd, Notes, PSI);
    }

This above method does not return an ActionResult, but a primitive type but this is called via ajax and can return bool true or false

Upvotes: 0

Views: 1096

Answers (1)

dotnetstep
dotnetstep

Reputation: 17485

You HomeController as Method that return Json

if your web url like this http://yourdomain/home/GetPartNumbers it return Json result.

Now as per your edit you have method called SaveEvent. Which is called as http://yourdomain/home/SaveEvent. This also called by MVC pipeline. When you return result like true or false or any string which is not type of ActionResult , it get converted ContentResult and return to your AJAX call.

Here Web API route will not get called.

Even when WEB API is not available at that time Developer use MVC as REST as well.

To check further put following code in your controller and you can see which result type your method get converted when you not return actionresult.

protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string resultType = filterContext.Result.GetType().Name;
            base.OnActionExecuted(filterContext);
        }

If you don't want such action get called then you have explicitly set NonAction attribute for them or make then private.

[NonAction]
        public object Test()
        {
            return new { test = "Jinal" };
        }

Upvotes: 2

Related Questions