jQuery的Ajax调用WEB API
我试图做一个简单的jQuery ajax调用到Web API方法。
I'm trying to make a simple jquery ajax call to a WEB API method.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'http://redrock.com:6606/api/values/get',
dataType: "jsonp",
crossDomain: true,
success: function (msg) {
alert("success");
},
error: function (request, status, error) {
alert(error);
}
});
});
</script>
WEB API操作:
WEB API action:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
Ajax调用不打的WEB API。我得到在浏览器控制台下面的错误。
ajax call does not hitting the WEB API. I get the below error in browser console.
GET http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850 400(错误请求)
GET http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850 400 (Bad Request)
您还没有包括在code的路线设置,但假设它是正确的,问题是由事实,你有一个名为可能引起您的WebAPI方法获取您尝试使用POST请求来打一段时间。这是因为的WebAPI试图找出HTTP动词从动作的名称。
You haven't included the code for the route setup, but assuming it is correct, the problem is probably caused by the fact that you have named you WebApi method 'Get' while you are trying to hit it using a POST request. This happens because WebApi tries to figure out the HTTP verb from the action name.
我会建议要么重命名操作或添加 [HttpPost]
属性为您的操作方法。你也可以试试 WebApiRouteDebugger 包。
I would suggest either renaming the action or adding the [HttpPost]
attribute to your action method. You may also try the WebApiRouteDebugger package.