简体   繁体   中英

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,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM