【问题标题】:ASP.NET Web API Routing IssueASP.NET Web API 路由问题
【发布时间】:2012-07-16 13:55:46
【问题描述】:

这是我修改的默认路由器:

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

这是控制器:

public class ReviewCycleController : ApiController
{

    private MrdSearchServices _mrss = new MrdSearchServices();


    // GET api/reviewcycle
    public IQueryable<MrdReviewCycle> GetReviewCycles()
    {

        return _mrss.GetAllReviewCycles();
    }


    // GET api/reviewcycle/Active
    public MrdReviewCycle GetReviewCycle(String is_active)
    {
        if (!is_active.ToLower().Equals("active"))
        {
            string url = new Uri(Request.RequestUri, "/api/ReviewCycle/Active").ToString();
            var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("No Review Cycle with State of '{0}' could be found. The only acceptable value is 'Active'. Request should be made to {1}.", is_active, url)),
                ReasonPhrase = "Review Cycle Not Found!"
            };
            throw new HttpResponseException(resp);
        }

        return _mrss.GetActiveReviewCycle();
    }
}

但是当我打电话给http://localhost:2515/api/ReviewCycle/asdf 或http://localhost:2515/api/ReviewCycle 时,我没有得到预期的结果。我得到的是return _mrss.GetActiveReviewCycle();的结果。

我到底做错了什么?

谢谢 埃里克

【问题讨论】:

    标签: asp.net-mvc-routing asp.net-mvc-4 asp.net-web-api


    【解决方案1】:
    public MrdReviewCycle GetReviewCycle(String is_active)
    

    应该是:

    public MrdReviewCycle GetReviewCycle(String addParam)
    

    另外请注意,一个路由中只能有 1 个可选参数,并且该参数必须是最后一个。在您的路线定义中,您有 2 个可选参数({id} 和 {addParam}),这是不可能的。

    调用 url 也应该是(一旦你将 {id} 参数设为非可选):

    http://localhost:2515/api/ReviewCycle/123/active
    

    我在您的代码中看到的另一个潜在问题是,在您的路由中没有 {action} 标记,这意味着您应该使用标准 HTTP 动词作为操作名称,而不是 GetReviewCycle。应该是 Get 并且由于您在 ReviewCycle 控制器上使用了 GET 动词,因此将调用此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多