【发布时间】:2019-05-19 07:29:19
【问题描述】:
我想通过 jQuery 在 .NET Core 中调用我的 WEB API,如下所示:
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
JsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
return Json(welCome, JsonSettings);
}
catch(Exception ex)
{
throw ex;
}
}
还有 jQuery 调用者:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "http://localhost:5000/api/mycontroller/GetText?callback=?",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
if (data.success) {
alert('Success -> ' + JSON.stringify(data.statusText));
}
},
error: function (data) {
alert('Error -> ' + JSON.stringify(data.statusText));
}
});
});
</script>
API 调用成功,但它似乎会重定向到我的 Ajax 中的错误函数,并显示带有“成功”的错误警报,因为它是 statusText。我的意思是:错误 -> “成功” 我不知道为什么会这样?
我想在警报命令中打印welCome 作为成功结果。
另外请注意,我是从另一个项目调用此 API,我的意思是 jQuery 的 AJAX 代码在另一个项目中。我不确定它是否重要。
jQuery 的 AJAX 调用者路径:file:///C:/Users/Me/Desktop/Path/index.html
API地址:C:\Users\Me\Documents\Visual Studio 2017\Projects\ThisProject\MyAPI
还有这个API的URL:url: "http://localhost:5000/api/mycontroller/GetText",
【问题讨论】:
-
它期望接收一个 json 对象,你正在发送一个字符串返回
-
@Sujit.Warrier 那么,
return Json不应该返回一个 json 吗? -
删除
?callback=?将起作用。你会看到它先发送option请求,然后在开发工具中发送get请求。
标签: javascript c# jquery ajax asp.net-core-webapi