从AngularJS调用Web API时,以“数据":null,“状态":-1的形式获取响应 [英] Getting the response as "data":null,"status":-1 when calling web api from AngularJS

查看:76
本文介绍了从AngularJS调用Web API时,以“数据":null,“状态":-1的形式获取响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Angular JS 1.6.0调用Web API GET方法,并收到以下错误:-

I am trying to call Web API GET Method from Angular JS 1.6.0 and getting the following error:-

可能未处理的拒绝:{数据":null,状态":-1,配置":{方法":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":回调","url":" http://localhost:51972/api/video ",标题":{"Accept":"application/json,text/plain,/}}," statusText:"}

Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:51972/api/video","headers":{"Accept":"application/json, text/plain, /"}},"statusText":""}

当我从Fiddler 4调用相同的GET方法并返回JSON文本时,我得到了正确的JSON响应.

I am getting the proper JSON response when I call the same GET method from Fiddler 4 and returning JSON Text.

请注意,我的WEB API和Angular JS代码位于不同的目录中.

Please note that my WEB API and Angular JS code are in different directory.

根据Dez的评论,我修改了WebApiConfig.cs以从WebAPI返回JSON响应

As per Dez's comment I have modified WebApiConfig.cs to return JSON response from WebAPI

WebApiConfig.cs

WebApiConfig.cs

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
    }

VideoController.cs

VideoController.cs

public class VideoController : ApiController
{
        [Route("api/video")]
        public List<VideoViewModel> GetVideo()
        {
            List<VideoViewModel> video = new List<VideoViewModel>();
            video.Add(new VideoViewModel { Name = "Hello World", Desc = "Hello World Desc" });
            video.Add(new VideoViewModel { Name = "Hello World1", Desc = "Hello World Desc1" });
            return video;
        }
} 

当我输入' http://localhost:51972/api/video '并点击我得到正确的响应(JSON),如下所示:-

When I type 'http://localhost:51972/api/video' and hit then I get proper response(JSON) as below:-

 [{"Name":"Hello World","Desc":"Hello World Desc"},{"Name":"Hello World1","Desc":"Hello World Desc1"}]

Home.html

Home.html

<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
    <script src="../Scripts/AngularControllers/AddVideoController.js"></script>
</head>
<body ng-app="modVid" ng-controller="ctrlVidAdd">
      <table class="table">
        <tr>
            <th>Name</th>
            <th>Desc</th>
       </tr> 
       <tr ng-repeat="a in selectedDisplay">
            <td>{{a.Name}}</td>
            <td>{{a.Desc}}</td>
        </tr>
    </table>
</body>

AddVideoController.js

AddVideoController.js

var myApp = angular.module("modVid", []);
myApp.controller("ctrlVidAdd", function ($scope, $http) {
$http.get('http://localhost:51972/api/video').then(function (response) {
        alert("Hello");
        $scope.selectedDisplay = response.data;
    });
});

当我尝试从Angular JS调试WEB API Get调用时,我可以看到它正在调用Web API Get方法,但没有从Web API返回任何信息.如您所见,我在$ http端的响应中添加了警报,该响应也未得到执行.

When I try to debug WEB API Get call from Angular JS then I can see that it is calling Web API Get method but nothing is returning from Web API. As you can see I put alert in the response at $http end which is also not getting executed as well.

任何帮助将不胜感激.

推荐答案

您可能需要启用CORS:

You probably need to enable CORS:

在您的WebApiConfig.cs文件中,添加以下内容:

In your WebApiConfig.cs file, add this:

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

CORS是浏览器检查的,以在使用脚本进行调用时执行相同的原始策略.使用Fiddler之类的东西或直接在浏览器中访问api时,您将看不到它.

CORS is a check by the browser to enforce same origin policy when the call is made using scripting. You won't see it when using something like Fiddler or when accessing the api directly in the browser.

这篇关于从AngularJS调用Web API时,以“数据":null,“状态":-1的形式获取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆