【发布时间】:2015-09-10 21:53:03
【问题描述】:
我有一个 MVC 应用程序,其中包含几个简单的页面,这些页面主要在 Web API 调用上运行。为简单起见,我想将它们包含在同一个项目中。我可以很好地启动并导航到我的页面,但是当我尝试通过 Ajax 调用我的 API 时,我不断收到 404 错误 - 它找不到 API 函数。
这是我的 javascript 文件:
$(document).ready(function () {
//set the login button to call our test API function
document.getElementById("login_submit").addEventListener("click", GetUser);
});
function GetUser() {
var response = $.ajax({
url: '/api/User',
method: 'GET',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Success!");
},
error: function (request, status, error) {
alert(error);
}
});
}
这是我的控制器:
namespace MyProject.Controllers.API
{
public class UserController : ApiController
{
// GET api/<controller>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
[HttpGet]
public string Get(int id)
{
return "value";
}
}
}
API 控制器位于我项目的 Controllers 文件夹中它们自己的文件夹(称为“API”)中 - 这就是名称空间在此示例控制器上包含“API”的原因。
当我在浏览器上使用 F12 来捕获发送的请求时,我可以看到我的调用包含以下信息:
Request URL: http://localhost:50035/api/User
Request Method: GET
Status Code: 404 / Not Found
现在我的理解是,这应该找到名称为 UserController 的 API,并找到带有 [HttpGet] 标签且不带参数的函数,然后返回字符串数组(“value1”、“value2”)。相反,它什么也没找到。
最后,这是我的路由配置(是的,它正在 Global.asax 上初始化):
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}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
更新:
根据我目前收到的反馈,我移动了我的 Global.asax 配置。它现在看起来像这样:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
现在,当我调用我的 API 函数时,我得到...待处理。它不返回成功消息。它只是挂起。我没有得到“成功!”警告。
【问题讨论】:
-
在 Global.asax Application_Start() 方法中注册路由的顺序是什么?如果你在 WebAPI 路由之前注册 MVC 路由,那么 api 路由将失败!
-
通过注册MVC路由重现问题before WebApi路由。
-
如果在 User 控制器的 Get() 方法中设置断点,它会被命中吗?
-
是的,Get() 上的断点被击中。有趣的是,尝试下面的 codeMonkey 建议有效(这与我认为到目前为止我对 API 调用的理解相反),并且我不再收到挂起的“待处理”请求。看起来它现在工作正常?
-
如果你支持我的评论,那么永远爱你 ;)
标签: c# ajax asp.net-mvc routing asp.net-web-api