Web API 2 自定义控制器方法。路由问题

Web API 2 Custom Controller method. Routing issue

这是我的 Global.asmx

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

这是我的 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 }
        );
    }
}

这是我的 ApiController

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

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

如果我浏览到 http://localhost:52072/api/hello/get,那么我会按预期收到 "get method"。

如果我浏览到 http://localhost:52072/api/hello/SayHello,则会出现 404 not found 错误。

有什么想法吗?

来源:Attribute Routing in ASP.NET Web API 2

更新路线

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

你也可以使用路由前缀

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

设置属性路由匹配您的请求url,您需要在方法名称中添加前缀Get,或者需要在方法之前放置[HttpGet] annpotation

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

或重命名方法名称并在其前面添加前缀Get

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