使用 Visual Studio 2012 及其 ASP.NET 开发服务器,对于我第一次涉足 ASP.NET 来说,一切似乎都运行良好。我的 Web API 调用使用 jquery 返回的数据。在部署到 IIS Express 7.5 以开始学习身份验证/授权时,我在 getJSON 调用中遇到了障碍:
GET http://localhost/api/OSList 404 (Not Found)
WebApi配置
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
获取JSON
$.getJSON("/api/OSList", null)
.success(
function(data) {
var mappedOs = $.map(data, function(item) {
return new Os(item.ID, item.Name, item.PatchLevel);
});
self.OSs(mappedOs);
}
);
这一切都在开发服务器上运行...是否是我在 IIS 中没有正确设置的东西会阻止此操作?
编辑:添加了 Controller 代码,这对我来说显然是一个错误。这是默认的开发工作室自动生成的。
public class OSListController : ApiController
{
private readonly TrendDataEntities _db = new TrendDataEntities();
// GET api/OSList
public IEnumerable<OS> GetOS()
{
return _db.OS.AsEnumerable();
}
}
HomeController 使用:
public ActionResult OSList()
{
ViewBag.Title = "OS List";
ViewBag.Message = "";
return View("~/Views/Home/Admin/OSList.cshtml");
}
最佳答案
Visual Studio 开发服务器在特定端口上运行您的应用程序,以便 http://localhost:<port>/api/OSList
将工作。如果将应用程序部署到 IIS,您的应用程序不会与其他应用程序一起在专用端口上运行,而是在 80(默认情况下)上运行。在这种情况下,您的 URI 还必须包含您的应用程序名称。因此,如果您的应用程序名称是 MyWebApi,那么您的 URI 必须是 http://localhost/mywebapi/api/OSList
。 getJSON 必须类似于 $.getJSON("/mywebapi/api/OSList", null)
.
关于jquery - getJSON Web API 可在开发服务器上运行,但 IIS Express 7.5 抛出 404 未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17307824/