Вызов запроса GET возвращает неверный результат - PullRequest
2 голосов
/ 19 мая 2019

Я хотел бы вызвать свой WEB API в .NET Core из jQuery, как показано ниже:

[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 из другого проекта, я имею в виду, что AJAX-код jQuery находится внутри другого проекта. Я не уверен, важно это или нет.

Путь вызывающего абонента в JQuery: file:///C:/Users/Me/Desktop/Path/index.html

Адрес API: C:\Users\Me\Documents\Visual Studio 2017\Projects\ThisProject\MyAPI

И URL этого API: url: "http://localhost:5000/api/mycontroller/GetText",

1 Ответ

0 голосов
/ 19 мая 2019

Попробуйте код 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) {

      }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...