【问题标题】:The GET request call returns wrong resultGET 请求调用返回错误结果
【发布时间】: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


【解决方案1】:

按以下方式尝试 C# 代码:

[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
    try
    {
        string welCome = "Test";    
        return Ok(new { message = welCome });
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

按以下方式尝试 Jquery 代码:

$.ajax({
       contentType: 'application/json; charset=utf-8',
       dataType: 'json',
       type: 'GET',
       url: 'http://localhost:5000/api/mycontroller/GetText',
       success: function (response) {
       alert('Success' + response.message);
      },
      failure: function (response) {

      }
});

【讨论】:

  • 感谢您的回答。但是什么都没有改变,我仍然没有在成功函数中得到alert('Success' + response.message);,但是正如我所说,我的 API 正在成功运行。
  • 另外?callback=? 是必要的,应该附加在我的网址之后,因为没有它,浏览器中的请求方法将显示为OPTION 而不是GET
  • 只是这部分在API调用error: function (data) { alert('Error -&gt; ' + JSON.stringify(data.statusText)); }后执行,返回状态为200。
  • 可能是您遇到了 CORS 错误。确保您已配置 CORS。
  • 什么是 CORS?我该如何配置它?
猜你喜欢
  • 2021-12-06
  • 2020-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 2013-01-21
相关资源
最近更新 更多