CathalMF CathalMF - 1 month ago 23
C# Question

Web API 2 Custom Controller method. Routing issue

Here is my Global.asmx

public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}


Here is my WebApiConfig class.

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

// Web API routes
config.MapHttpAttributeRoutes();

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


Here is my ApiController

public class HelloController : ApiController
{
public string Get()
{
return "get method";
}

[Route("SayHello")]
public string SayHello()
{
return "Hello Jim";
}
}


If I browse to
http://localhost:52072/api/hello/get
then I will receive back "get method" as expected.

If I browse to
http://localhost:52072/api/hello/SayHello
then it errors with a
404 not found
.

Any ideas?

Answer

Source : Attribute Routing in ASP.NET Web API 2

Update route

public class PaymentController : ApiController {
    public string Get() {
        return "get method";
    }

    //GET api/payment/SayHello
    [HttpGet]    
    [Route("api/payment/SayHello")]
    public string SayHello() {
        return "Hello Jim";
    }
}

You could also use route prefix

[RoutePrefix("api/payment")]
public class PaymentController : ApiController {
    //GET api/payment/Get
    [HttpGet]
    [Route("Get")]
    public string Get() {
        return "get method";
    }
    //GET api/payment/Sayhello
    [HttpGet]
    [Route("SayHello")]
    public string SayHello() {
        return "Hello Jim";
    }
}
Comments