user3177519 user3177519 - 3 months ago 34
C# Question

How to Use MVC Controller and WebAPI Controller in same project

I am trying to use MVC Controller and WebAPI controller in same project but i got 404 errors for webapi . I started project as MVC Project in vs 2015 but then added webapi controlle and with default code it is giving 404 error

what could be possible solution . I have tried some solution on Stackoverflow but they didn't worked one of them is below link (Accepted Answer over there )
All ASP.NET Web API controllers return 404

Global.ASAX File Code :

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);

}


WEBAPI.CONFIG FILE

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 }
);

}
}


Route Config File Code

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 }
);

}
}


WebAPI Controller CODE

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)
{
}
}
}


ALSO GETTING NUGET RESTORE ERROR IN SAME SOLUTION
Error Nuget failed to restore PNG

Answer

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);
}