无法在MVC 5应用程序中的Web API 2控制器中访问Action。

27 浏览
0 Comments

无法在MVC 5应用程序中的Web API 2控制器中访问Action。

我尝试按照默认的Web API教程进行操作:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

这是我的操作步骤:

1)在我的WebApiConfig中添加了动作路由:

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

2)在我的导航栏中添加了一个链接,并通过客户端JavaScript调用:

检索下一个

3)这是我的视图:

        

下一个条形码

没有可用的条形码

4)这是我的简单ApiController,只有一个动作:

public class BarcodeController : ApiController
{
    [HttpGet]
    public IHttpActionResult RetrieveNext()
    {
        string barcode = "123456";
        if (barcode == null)
        {
        return NotFound();
            }
        return Ok(barcode);
    }
}

当我点击链接时,

中显示Error: Not Found,这意味着JavaScript可以运行,但是动作没有被调用。

以下是调用详细信息:

enter image description here

我在动作中设置了断点,但无法到达这段代码...

我错过了什么?

0
0 Comments

问题的原因是在于global.asax文件中的代码顺序。在将Web API添加到项目中时,Visual Studio会打开一个readme.txt文件,其中包含一些提示,告诉你应该将代码放在global.asax文件的哪个位置。然而,这个文件并没有明确指出应该将代码放在哪里。

解决方法是将Web API相关的代码放在Application_Start方法中的正确位置。具体来说,将GlobalConfiguration.Configure(WebApiConfig.Register)代码放在其他代码之前,如下所示:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register); //将这行代码放在第二个位置
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

这样修改之后,Web API的Action就可以正常访问了。

0