我有 ASP.Net MVC 4 Web API 项目。在此项目的 Controller 中,我创建了返回类型为 HttpResponseMessage 的所有方法。以下是我的 Web API Controller 的代码。
[HttpPost]
public HttpResponseMessage RegisterNewUser(string UserName, string AuthToken)
{
JsonResult objJR = new JsonResult();
JUser objJU = new JUser();
HttpResponseMessage response;
try
{
response = Request.CreateResponse(HttpStatusCode.ExpectationFailed, objJR);
return response;
}
catch (Exception e)
{
return CatchError(e.Message);
}
}
[HttpGet]
public HttpResponseMessage GetUserProfile(int UserID, string AuthToken)
{
JsonResult objJR = new JsonResult();
JUser objJU = new JUser();
HttpResponseMessage response;
BCUsers objBCUsers = new BCUsers();
try
{
response = Request.CreateResponse(HttpStatusCode.OK, ds);
}
return response;
}
catch (Exception e)
{
return CatchError(e.Message);
}
}
然后我在phonegap中创建了移动应用程序,我尝试从js文件调用Web API方法,以下是该代码
<script type="text/javascript">
var CommonURL = "http://localhost/api/common/";
function GetCoachProfile(UserID,AT) {
alert('2');
alert(UserID + AT);
$.ajax({
url: CommonURL + 'GetUserProfile?UserID=' + UserID + '&AuthToken=' + AT,
type: 'GET',
datatype: 'json',
contenttype: "application/json",
success: function (data) {
alert('3');
alert(data);
},
error: function(xhr,textStatus,errorThrown) {
alert(xhr.responseText);
alert(textStatus);
alert(errorThrown);
}
});
}
</script>
GetCoachProfile
函数在 HTML 页面的按钮单击时被调用,我放置在 Web API 方法上的调试点在单击按钮后也会被命中,所有 Web API 方法在 AJAX 调用返回后仍然成功执行它执行错误循环并且不成功,如果有人帮助我,请帮助我,我是phonegap和jQuery的新手。
最佳答案
通过在我的 Web api 项目的 web.config 文件中添加以下代码行来解决,该问题是由于跨平台造成的。
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
关于jquery - 如何在移动jquery中调用web api方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30617754/