Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Route and RoutePrefix issue within asp.net web api application

I have a web api application in which I need to change the routing configuration.

Javascript

$.ajax({
        type: "GET", 
        url: "api/collaborators",
        success: function (data) {

        }});

In controller

[RoutePrefix("api/")]
public class AccountManageController : BaseApiController
{
    [Authorize]
    [HttpGet]
    [Route("collaborators")]
    public IEnumerable<CollaborateurModel> GetAllCollaborators() {...}
}

I get an exception indicating that the service is not found !! besides, even when I put the url directly in the browser I get the same result.

WebApiConfig.cs

public static class WebApiConfig
{
    public static string UrlPrefix { get { return "api"; } }
    public static string UrlPrefixRelative { get { return "~/api"; } }

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

        config.Routes.MapHttpRoute(
            name: "DefaultApi2",
            routeTemplate: WebApiConfig.UrlPrefix + "/{controller}" 
        ); 
    }
}

I need to know

  1. What are the reasons of the problem ?
  2. How can I fix it?

Thanks,

Upvotes: 0

Views: 652

Answers (2)

Dmitry
Dmitry

Reputation: 16795

Attribute routing and template routing are two different things.

You do not need to add custom attributes if your routing rules 'matches' configured route templates.

But if you want use attributes for 'special' routes/actions - use must add MapHttpAttributeRoutes() into you route registration logic (before first config.Routes.MapHttpRoute... call).

Without this, your method GetAllCollaborators is accessible via /api/AccountManage/GetAllCollaborators url (according to your first route template "DefaultApi")

Upvotes: 1

Nkosi
Nkosi

Reputation: 247088

1) You are trying to use Attribute Routing ASP.NET Web API 2 but you are not Enabling Attribute Routing

2) This is how you fix it.

public static class WebApiConfig {

    public static string UrlPrefix { get { return "api"; } }
    public static string UrlPrefixRelative { get { return "~/api"; } }

    public static void Register(HttpConfiguration config) {
         //Enable Web API Attribute routing.
         config.MapHttpAttributeRoutes();

        // Other Web API configuration
        config.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{action}/{id}",
         defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
           name: "DefaultApi2",
           routeTemplate: WebApiConfig.UrlPrefix + "/{controller}" 
        );
    }
}

Upvotes: 1

Related Questions