Web API route to action name

前端 未结 4 1652
刺人心
刺人心 2020-12-14 09:11

I need a controller to return JSON to be consumed by JavaScript so I inherited from the ApiController class but it isn\'t behaving as I expected. The Apress bo

相关标签:
4条回答
  • 2020-12-14 09:44

    Adding additional information on above answer. Adding RoutePrefix would fix the issue sometimes. Hope it helps

    Controller

        [RoutePrefix("api/Services")]
        public class ServicesController : ApiController
        {
            [System.Web.Http.AcceptVerbs("GET", "POST")]
            [System.Web.Http.HttpGet]
            [Route("MethodFruit")]
            public string[] MethodFruit()
            {
                return new string[] { "Apple", "Orange", "Banana" };
            }
        }
    

    In config

    routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional } );
    
    0 讨论(0)
  • 2020-12-14 09:45

    Yep... generally you have to follow the default naming convention expected by ASP.NET WEB API.

    Check this official doc:

    Routing in ASP.NET Web API

    If you do not want to follow the convention, you can try the Routing by Action Name section described in the above linked doc.

    Routing by Action Name

    With the default routing template, Web API uses the HTTP method to select the action. However, you can also create a route where the action name is included in the URI:

    routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional } );
    

    In your case, you'd have to do this:

    [HttpGet]
    public string[] MethodFruit()
    {
        return new string[] { "Apple", "Orange", "Banana" };
    }
    
    0 讨论(0)
  • 2020-12-14 09:52

    i was facing same issue, i found that on my code

    using System.Web.Mvc; 
    

    i've imported Mvc intead of using System.Web.Http. so it was using Mvc routing not webApi route. i've replaced that with

    using System.Web.Http 
    

    and it works for me. i'm adding my answer so newbies won't repeat the same mistake

    0 讨论(0)
  • 2020-12-14 10:07

    If you want Web API to look for the action name when routing, change the WebApiConfig.cs class in the App_Start folder to this:

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

    Then you can just make a GET request to

    http://mysite/api/Services/MethodFruit
    
    0 讨论(0)
提交回复
热议问题