这是我的Global.asmx
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
这是我的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 }
);
}
}
这是我的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
。
有什么想法吗?
答案 0 :(得分:0)
来源: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";
}
}
答案 1 :(得分:0)
将属性路由匹配设置为您的请求网址,并且您需要在方法名称中加上Get
前缀,或者需要在方法之前放置[HttpGet]
annotation
[HttpGet]
[Route("api/payment/SayHello")]
public string SayHello()
{
return "Hello Jim";
}
或重命名方法名称和前缀Get
[Route("api/payment/SayHello")]
public string GetSayHello()
{
return "Hello Jim";
}