【发布时间】:2016-01-13 19:56:24
【问题描述】:
您好,我已经开始学习 Web API 我目前有一个 Web Api 控制器,位于我的项目的根目录(不在文件夹中),如下所示
public class LearnWebApi : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
现在我有一个家庭控制器,它位于控制器文件夹中,视图位于视图文件夹中。现在在视图上我有一个按钮,当我单击此按钮时,我想调用 Api Web Controller Get Method 并传入 ID 2 例如我在以下位置放置了一个断点
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
但它没有被击中,而是我在浏览器中收到消息说
404 Not Found - http://localhost:27774/~/api/LearnWebApi/Get/5"
我的 jquery 在这里
<h2>Index</h2>
<button id="PressMe">Press me</button>
<script type="text/javascript">
$(document).ready(function () {
$('#PressMe').click(function () {
$.ajax({
type: "POST",
dataType: "json",
// data: source,
url: '~/api/LearnWebApi/Get/5', // url of Api controller not mvc
success: function (data) {
alert("Redirect true !");
},
error: function () {
alert('erere');
}
});
return false;
});
});
</script>
这是我的 WebApiConfig
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}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
以下是我的项目是如何构建的
现在我想这可能与我指定的 URL 有关,但我不确定是否有任何帮助?
【问题讨论】:
标签: jquery asp.net-mvc asp.net-web-api