Routes Conflict in Web.Mvc and Web.HTTP Routes. When To use which.

Code Snippets 4 U

When creating a web API with .NET standard there are two Route namespaces available.

  1. System.Web.Mvc.Route()
  2. System.Web.Http.Route()

First one used when the controller class is extended by your class in which you are defining the attribute route.

e.g.

 public class HomeController : Controller
    {
        [System.Web.Mvc.Route()]
        public ActionResult Index()
        {
            this.HttpContext.Response.AddHeader("status","404");
            return Content("Not Found");
        }
    }

Second one used when the ApiController is extended by your class e.g.

 [System.Web.Http.Route("api/getallinfo")]

      public class GetAllInfoController : ApiController
    {
        [System.Web.Http.HttpGet]
        public List<DbSchema> Index()
        {
            return AllDataStore.AllData.ToList();
        }
    }

The Web API config file will look like below after CORS enabled and XML disabled for response formats:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
           // do not include the forward slash for origin urls

            EnableCorsAttribute cors = new EnableCorsAttribute("http://localhost:3000", "*", "*");
            config.EnableCors(cors);

            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
    }

You have to add CORS nuget package in order to CORS to work properly.

Route Config file will look like below after enabling Mvc route attributes:

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

Global.asax will look like below:

 public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

fifty − = forty two