获取方法无法在web api中工作

Nir*_*ole 2 c# asp.net-web-api asp.net-web-api-routing

嗨,我正在开发web api2和angularjs中的一个应用程序.从angularjs访问URL时我遇到了一些路由问题.

我试图访问下面的网址.

var url = '/api/projects/4/processes';
Run Code Online (Sandbox Code Playgroud)

我的控制器代码如下所示.

[RoutePrefix("api/processes")]
public class processesController : ApiController
{      
    [ActionName("projects/{projectsId}/processes")]
    public HttpResponseMessage Get(int id)
    {
        return Request.CreateResponse(HttpStatusCode.OK, "");
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到404错误.我无法点击网址.

这是我的webapi.config文件.

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

任何帮助,将不胜感激.

Nko*_*osi 5

首先确保在基于约定的路由之前启用属性路由.

config.MapHttpAttributeRoutes();

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

如果预期的网址是,/api/projects/4/processes那么给定的操作需要更新其路由模板以匹配.控制器已经有一个路由前缀,但可以通过在路由模板前面添加波形符来覆盖它~

在method属性上使用波浪号(〜)来覆盖路由前缀:

//GET /api/projects/4/processes
[HttpGet]    
[Route("~/api/projects/{projectsId:int}/processes")]
public HttpResponseMessage Get(int projectsId) { ... }
Run Code Online (Sandbox Code Playgroud)

来源:ASP.NET Web API 2中的属性路由