【问题标题】:Web API Routing - Only actions with a URI parameter workWeb API 路由 - 只有带有 URI 参数的操作才有效
【发布时间】:2014-07-06 01:19:19
【问题描述】:

我有一个运行良好的 Web API 项目。我将它与一个 MVC 项目合并,现在只有带有 URI 参数的操作才有效。所有其他操作都以 404 Not Found 结束,甚至找不到控制器。

这是我在 WebApiConfig 中的内容(标准内容):

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

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

这是控制器类:

[Authorize]
[RoutePrefix("api/WikiPlan")]
public class WikiPlanController : ApiController

以下是有效的操作:

http://localhost:2000/api/WikiPlan/SearchWikiPlans/baby
[AllowAnonymous]
[HttpGet]
[Route("SearchWikiPlans/{keyword}")]
[ResponseType(typeof(List<WikiPlanSearchResultViewModel>))]
public IHttpActionResult SearchWikiPlans(string keyword)

这是一个不工作的(它曾经在它自己的项目中工作):

http://localhost:2000/api/WikiPlan/TopWikiPlans
[AllowAnonymous]
[HttpGet]
[Route("TopWikiPlans")]
[ResponseType(typeof(List<TopWikiPlan>))]
public IHttpActionResult TopWikiPlans()

我不知道出了什么问题。感谢您的帮助!

【问题讨论】:

  • 请向我们展示类声明,
  • 您声称无效的网址是什么?
  • 是控制器类
  • 我通过将字符串参数添加到 TopWikiPlans 操作进行了测试,并且它有效。所以它似乎出于某种原因需要一个参数。
  • 为什么不直接使用 POST 请求而不是 GET?

标签: asp.net-mvc asp.net-web-api2 asp.net-web-api-routing asp.net-apicontroller


【解决方案1】:

感谢这个 Route Debugger 工具 (http://blogs.msdn.com/b/webdev/archive/2013/04/04/debugging-asp-net-web-api-with-route-debugger.aspx),我能够追踪损坏的 URL 并找出问题所在。

原来框架将损坏的 URL 与 MVC 路由而不是我的 API 路由进行匹配。所以我将调用转移到 Global.asax 中的 MVC 路由之上注册 API 路由,现在它匹配正确了。

【讨论】:

    猜你喜欢
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2017-08-30
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多