GET请求调用返回错误结果

时间:2019-05-19 07:29:20

标签: javascript c# jquery ajax asp.net-core-webapi

我想从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”,

1 个答案:

答案 0 :(得分:0)

以以下方式尝试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) {

      }
});
相关问题