Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use MVC Controller and WebAPI Controller in same project

I am trying to use an MVC Controller and a Web API controller in the same project, but I get 404 errors for the Web API. I started the project as an MVC project in VS 2015, but then added the Web API controller, and with the default code it is giving a 404 error.

What could be the possible solution? I have tried some solutions on Stack Overflow, but they didn't work. One I tried is the accepted answer from this question: All ASP.NET Web API controllers return 404

Global.asax:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);//WEB API 1st
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

RouteConfig:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Web API Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using O365_APIs_Start_ASPNET_MVC.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using O365_APIs_Start_ASPNET_MVC.Helpers;
using System.Threading.Tasks;

namespace O365_APIs_Start_ASPNET_MVC.Controllers
{
    public class MAILAPIController : ApiController
    {
        private MailOperations _mailOperations = new MailOperations();
        //async Task<BackOfficeResponse<List<Country>>>

        // GET: api/MAILAPI
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/MAILAPI/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/MAILAPI
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/MAILAPI/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/MAILAPI/5
        public void Delete(int id)
        {
        }
    }
}

I'm also getting an error restoring NuGet packages in the same solution:

An error occurred while trying to restore packages: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

like image 945
user3177519 Avatar asked Aug 29 '16 07:08

user3177519


People also ask

How do Web API and MVC work together in the same project?

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.

Can we use MVC controller as API controller?

Before I illustrate how an ASP.NET MVC controller can be used as an API or a service, let's recap a few things: Web API controller implements actions that handle GET, POST, PUT and DELETE verbs. Web API framework automatically maps the incoming request to an action based on the incoming requests' HTTP verb.

Can I add API controller to MVC project?

If you have MVC project and you need to add Web API controller to this project, it can be done very easy. 1. Add Nuget package Microsoft.

How can I call MVC controller action from Web API?

You just need to make sure that you get your URLs right, so WebApi calls your MVC controller via it's properly qualified route. To test this, write a simple MVC action which returns some Json data and call it in the browser. If you manage to craft the URL correctly you will see the data displayed in the browser.


2 Answers

You need to register the routing for web api BEFORE registering the routing for MVC, so basically your App_Start()function should look like this:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);//WEB API 1st
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);//MVC 2nd
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}
like image 178
Denys Wessels Avatar answered Oct 21 '22 11:10

Denys Wessels


You can write both configurations in the same file like this:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index",
                id = UrlParameter.Optional }
        );
    }

    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

In the Global.aspx file, edit your code like this:

protected void Application_Start()
{
   AreaRegistration.RegisterAllAreas();
   GlobalConfiguration.Configure(RouteConfig.Register); // WEB API 1st
   FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
   RouteConfig.RegisterRoutes(RouteTable.Routes); // MVC 2nd
   BundleConfig.RegisterBundles(BundleTable.Bundles);
} 
like image 39
Mukesh Prajapati Avatar answered Oct 21 '22 13:10

Mukesh Prajapati