简体   繁体   English

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

[英]Web API 2 Custom Controller method. Routing issue

Here is my Global.asmx 这是我的Global.asmx

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

Here is my WebApiConfig class. 这是我的WebApiConfig类。

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 这是我的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. 如果我浏览到http://localhost:52072/api/hello/get那么我将按预期收到“get method”。

If I browse to http://localhost:52072/api/hello/SayHello then it errors with a 404 not found . 如果我浏览到http://localhost:52072/api/hello/SayHello则会在404 not found时出错。

Any ideas? 有任何想法吗?

Source : Attribute Routing in ASP.NET Web API 2 来源: 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";
    }
}

Set attribute routing match with your request url, and either you need to prefix Get in the method name or need to put [HttpGet] annpotation before the method 设置属性路由与您的请求URL匹配,并且您需要在方法名称中加上Get或者在方法之前放置[HttpGet] annpotation

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

or rename method name and prefix Get before it 或重命名方法名称和前缀Get

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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