Specify default controller/action route in WebAPI using AttributeRouting
Asked Answered
D

5

9

How does one set the default controller to use when using AttributeRouting instead of the default RouteConfiguration that WebAPI uses. i.e. get rid of the commented code section since this is redundant when using AttribteRouting

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

       }
     }

If I comment the section above and try to run the webapi app, I get the following error since there is no default Home controller/action defined. HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.

How can I specify the route via Attribute routing for the Home controller/action?

EDIT: Code Sample:

 public class HomeController : Controller
{
    [GET("")]
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Help()
    {
        var explorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();
        return View(new ApiModel(explorer));
    }
}
Descender answered 28/4, 2013 at 17:29 Comment(2)
Since you wrote that you are using AttributeRouting, would you please provide a code sample in your question that shows a controller action marked with an AttributeRouting attribute?Koa
@Pete: I have updated the post to include the code sampleDescender
B
9

Have you tried the following:

//[RoutePrefix("")]
public class HomeController : Controller
{
    [GET("")]
    public ActionResult Index()
    {
        return View();
    }
}

This will add a route in the collection with url template as "" and defaults for controller and action to be "Home" and "Index" respectively.

Belfort answered 28/4, 2013 at 22:23 Comment(3)
The above does not seem to work. I have updated the post to include a code snippetDescender
could you also check if you are invoking attribute routing's extensionMapAttributeRoutes?Belfort
Yes in the RegisterRoutes method of AttributeRoutingHttp static classDescender
N
5

This worked for me. Add this to Register() in WebApiConfig class

config.Routes.MapHttpRoute(
                name: "AppLaunch",
                routeTemplate: "",
                defaults: new
                {
                    controller = "Home",
                    action = "Get"
                }
           );
Negrillo answered 4/2, 2015 at 22:5 Comment(0)
K
1

You need to install AttributeRouting (ASP.NET MVC) alongside AttributeRouting (ASP.NET Web API) that you have already installed.

The MVC and Web API packages are complimentary packages. Both dependent on the AttributeRouting.Core.* packages. AR for MVC is for routes on Controller methods; AR for Web API is for routes on ApiController methods.

Koa answered 18/6, 2013 at 16:9 Comment(2)
Are you suggesting installing both AttributeRouting for MVC alongside AttributeRouting for WebAPI?Descender
Yes, you need to add the MVC package. They are complimentary packages, both dependent on the AttributeRouting.Core.* packages. AR for MVC is for routes on Controller methods; AR for Web API is for routes on ApiController methods. (I edited my answer to make that clear)Koa
T
1

Enable the attribute routing in your WebApiConfig class located in the App_Start folder by putting the following code:

using System.Web.Http;

namespace MarwakoService
{
      public static class WebApiConfig
      {
            public static void Register(HttpConfiguration config)
            {
                // Web API routes
                config.MapHttpAttributeRoutes();

               // Other Web API configuration not shown.
            }
       }
 }

You can combine with the convention-based attribute:

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

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

Now go to your global.asax class and add the following line of code:

GlobalConfiguration.Configure(WebApiConfig.Register);

Your HomeController is an MVC controller. Try creating an API controller(let's say a CustomersController) and add your route attributes as follows:

[RoutePrefix("api/Product")]
public class CustomersController : ApiController
{
    [Route("{customerName}/{customerID:int}/GetCreditCustomer")]
    public IEnumerable<uspSelectCreditCustomer> GetCreditCustomer(string customerName, int customerID)
    {
        ...
    }

Hope it helps

Thornie answered 10/11, 2016 at 14:13 Comment(0)
D
1

A standard MVC application can have both MVC and Webapi support if you check both MVC and Webapi from the Create New Asp.net web application template.

You will need to do the following under RouteConfig.cs as your query is particular to MVC routes and not webapi ones:

public class RouteConfig
{
   public static void RegisterRoutes(RouteCollection routes)
   {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

   }
 }

Notice the line with "routes.MapMvcAttributeRoutes();" which provides attribute routes while the call to "routes.MapRoute(...)" should provide you with a conventional route to a default controller and action.

This is because attribute routing and conventional routing can be mixed. Hope that helps.

Destrier answered 20/8, 2017 at 20:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.