1 javascript ajax http asp.net-web-api angularjs
我目前正在研究ASP.NET WebApi和Angularjs
WebApi有一个方法
[System.Web.Http.AcceptVerbs("POST")]
[System.Web.Http.HttpPost]
public HttpResponseMessage SearchAddress(SearchDetails searchDetail)
{
//13.03993,80.231867
try
{
if (!WebSecurity.IsAuthenticated)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotAcceptable);
return response;
}
List<CollegeAddress> CollegeAddress = addressService.GetAddressFromDistance(17.380498, 78.4864948, 2000);
HttpResponseMessage responseData = Request.CreateResponse(HttpStatusCode.Accepted, CollegeAddress);
return responseData;
}
catch (Exception e)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound);
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
我必须从客户端调用此方法.
当我使用它调用此方法时Ajax,它不起作用,searchDetail如果我使用Ajax ,则method参数始终为null.
$.ajax({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
type: "json",
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
Run Code Online (Sandbox Code Playgroud)
但是当我通过HTTP请求调用该方法时,它正在工作.
$http({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
data: searchDetail,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
toastr.success('Account Created successfully!', 'Account Created');
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
Run Code Online (Sandbox Code Playgroud)
为什么?他们之间有什么区别?为什么Ajax不工作而HTTP是?
jQuery ajax()使用Content-type发送数据:x-www-form-urlencoded.
Angular $http使用Content-type发送数据:application/json
您的服务器显然需要JSON,但您$.ajax()为此设置了错误的调用.
根据文件:
method物业似乎不存在.type属性应该确定请求的类型(例如'GET','POST'等).application/json您可以使用该contentType属性.我自己没有尝试过,但这样的事情应该有效:
$.ajax({
type: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
contentType: 'application/json; charset=utf-8'
});
Run Code Online (Sandbox Code Playgroud)