![](/img/trans.png)
[英]Trying to call a specific GET method on my WebAPI, but getting HTTP 404 Not Found
[英]Call WebAPI GET yielding 404 not found
VS 2017,新建,项目,C#,ASP.NET Web应用程序,ASP.NET 4.5.2空模板。
未选中的文件夹和Webforms,MVC和WebAPI的引用。 后来通过Nuget添加了MS WebApi v5.4.2。
手动添加“ Controllers”文件夹。
xController.cs:
namespace v1.MyApiCallTheirApi.api
{
public class xController : ApiController
{
// GET api/<controller>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
index.html的:
<body>
<input type="button" value="Go" onclick="go()"/>
<script type="text/javascript">
function go()
{
alert("lafdla");
$.ajax({
type: "GET",
url: "/api/x",
success: alert("ok")
});
}
</script>
</body>
$ .ajax调用始终返回404。已经检查了this , that和许多其他内容。 到目前为止,我唯一的怀疑是它可能需要Global.asax进行路由配置,但是我认为在添加API之后,它应该为我自动添加一些隐藏的路由。
现在,您的应用程序不知道如何创建路由。 MVC无法自动知道,除非您提供有关每种代码类型的位置的指针。
因此,这里有两种解决方法(使用GlobalConfiguration实例):
a)基于惯例,使用地图路线方法。 没有其他地方需要任何进一步的更改。
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
b)使用控制器方法上的属性来定义实际路线。 然后在每个操作方法上添加route属性
config.MapHttpAttributeRoutes();
过度行动
[Route('api/myentity/get')
public entity GetEntity() { }
至于添加软件包,它仅为您提供WebAPI所需的相关dll,而不会进行任何其他更改
总结我的问题的原因和解决方案:
public class v1Controller : ApiController
,仅public class v1 : ApiController
不起作用。 Global.asax是可选的,但就像项目的_init()一样,在这里也是必须的,因为API需要路由。 无论此Api是由项目内的还是项目外的调用的,只要将其击中内置的App_Start即可初始化项目的所有内容。
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
通常在App_Start中的类中定义的API路由注册,约定名称为WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Either this Attribute Routing
config.MapHttpAttributeRoutes();
// Or this conventional Routing, but not together.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
从Nuget添加新程序包不会自动配置/向项目添加必要的项目。
MS WebApi是基于MVC路由开发的,如果需要MVC会感到困惑,这是一个很好的阅读资料 。 答案是否定的,您不需要MVC即可进行WebApi。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.