Javascript Angularjs$http无法从Asp.net webapi 4获取数据

Javascript Angularjs$http无法从Asp.net webapi 4获取数据,javascript,c#,asp.net,angularjs,asp.net-web-api,Javascript,C#,Asp.net,Angularjs,Asp.net Web Api,我正在尝试用Asp.NETWebAPI和Angularjs构建一个应用程序 我试图从API获取数据,但结果得到一个空错误 Asp.net web api代码 [RoutePrefix("api/user")] public class UserController : ApiController { [Route("login")] [HttpGet] public HttpResponseMessage login(str

我正在尝试用Asp.NETWebAPI和Angularjs构建一个应用程序

我试图从API获取数据,但结果得到一个空错误

Asp.net web api代码

    [RoutePrefix("api/user")]
    public class UserController : ApiController
    {
        [Route("login")]
        [HttpGet]
        public HttpResponseMessage login(string userId, string password)
        {
...code to fetch data
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
        this.get = function (url, headers = {}) {

        /// creating a defer
        var def = $q.defer();
        $http({
            url: url,
            dataType: 'json',
            method: 'GET',
            data: '',
            headers: headers

        }).success(function (data) {
            def.resolve(data);
        }).error(function (error) {
            def.reject(error);
        });

        return def.promise;
    };
网络配置

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

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


    var formatters = GlobalConfiguration.Configuration.Formatters;

    formatters.Remove(formatters.XmlFormatter);

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
{
  "log": {
    "version": "1.2",
    "creator": {
      "name": "WebInspector",
      "version": "537.36"
    },
    "pages": [],
    "entries": [
      {
        "startedDateTime": "2016-06-02T16:27:59.550Z",
        "time": 25.981999933719635,
        "request": {
          "method": "GET",
          "url": "http://localhost:62158/api/user/login?userId=undefined&password=abc",
          "httpVersion": "HTTP/1.1",
          "headers": [
            {
              "name": "Origin",
              "value": "http://localhost:8000"
            },
            {
              "name": "Accept-Encoding",
              "value": "gzip, deflate, sdch"
            },
            {
              "name": "Host",
              "value": "localhost:62158"
            },
            {
              "name": "Accept-Language",
              "value": "en-US,en;q=0.8,hi;q=0.6,und;q=0.4"
            },
            {
              "name": "User-Agent",
              "value": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36"
            },
            {
              "name": "Accept",
              "value": "application/json, text/plain, */*"
            },
            {
              "name": "Referer",
              "value": "http://localhost:8000/"
            },
            {
              "name": "Connection",
              "value": "keep-alive"
            }
          ],
          "queryString": [
            {
              "name": "userId",
              "value": "undefined"
            },
            {
              "name": "password",
              "value": "abc"
            }
          ],
          "cookies": [],
          "headersSize": 429,
          "bodySize": 0
        },
        "response": {
          "status": 200,
          "statusText": "OK",
          "httpVersion": "HTTP/1.1",
          "headers": [
            {
              "name": "Pragma",
              "value": "no-cache"
            },
            {
              "name": "Date",
              "value": "Thu, 02 Jun 2016 16:27:59 GMT"
            },
            {
              "name": "Server",
              "value": "Microsoft-IIS/8.0"
            },
            {
              "name": "X-AspNet-Version",
              "value": "4.0.30319"
            },
            {
              "name": "X-Powered-By",
              "value": "ASP.NET"
            },
            {
              "name": "Content-Type",
              "value": "application/json; charset=utf-8"
            },
            {
              "name": "Cache-Control",
              "value": "no-cache"
            },
            {
              "name": "X-SourceFiles",
              "value": "=?UTF-8?B?QzpcVXNlcnNca2lyXERlc2t0b3BcRSBEcml2ZVxXb3JrIExpdmVcTml0aW4gS0sgU29mdHdhcmVcVmlkZW9MaWJyYXJ5XHByb2plY3RcVmlkZW9MSWJyYXJ5XFZpZGVvTElicmFyeVxhcGlcdXNlclxsb2dpbg==?="
            },
            {
              "name": "Content-Length",
              "value": "46"
            },
            {
              "name": "Expires",
              "value": "-1"
            }
          ],
          "cookies": [],
          "content": {
            "size": 0,
            "mimeType": "application/json",
            "compression": 447,
            "text": ""
          },
          "redirectURL": "",
          "headersSize": 447,
          "bodySize": -447,
          "_transferSize": 0,
          "_error": ""
        },
        "cache": {},
        "timings": {
          "blocked": 2.24999990314245,
          "dns": -1,
          "connect": -1,
          "send": 0.19500008784235012,
          "wait": 22.8659999556839,
          "receive": 0.6709999870509336,
          "ssl": -1
        },
        "serverIPAddress": "[::1]",
        "connection": "15008"
      }
    ]
  }
}
角度Js代码

    [RoutePrefix("api/user")]
    public class UserController : ApiController
    {
        [Route("login")]
        [HttpGet]
        public HttpResponseMessage login(string userId, string password)
        {
...code to fetch data
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
        this.get = function (url, headers = {}) {

        /// creating a defer
        var def = $q.defer();
        $http({
            url: url,
            dataType: 'json',
            method: 'GET',
            data: '',
            headers: headers

        }).success(function (data) {
            def.resolve(data);
        }).error(function (error) {
            def.reject(error);
        });

        return def.promise;
    };
结果

当我试图通过点击API URl来
获取结果时,我得到的是错误
null

如果我在web浏览器中打开url,那么它将返回JSON

网络日志

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

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


    var formatters = GlobalConfiguration.Configuration.Formatters;

    formatters.Remove(formatters.XmlFormatter);

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
{
  "log": {
    "version": "1.2",
    "creator": {
      "name": "WebInspector",
      "version": "537.36"
    },
    "pages": [],
    "entries": [
      {
        "startedDateTime": "2016-06-02T16:27:59.550Z",
        "time": 25.981999933719635,
        "request": {
          "method": "GET",
          "url": "http://localhost:62158/api/user/login?userId=undefined&password=abc",
          "httpVersion": "HTTP/1.1",
          "headers": [
            {
              "name": "Origin",
              "value": "http://localhost:8000"
            },
            {
              "name": "Accept-Encoding",
              "value": "gzip, deflate, sdch"
            },
            {
              "name": "Host",
              "value": "localhost:62158"
            },
            {
              "name": "Accept-Language",
              "value": "en-US,en;q=0.8,hi;q=0.6,und;q=0.4"
            },
            {
              "name": "User-Agent",
              "value": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36"
            },
            {
              "name": "Accept",
              "value": "application/json, text/plain, */*"
            },
            {
              "name": "Referer",
              "value": "http://localhost:8000/"
            },
            {
              "name": "Connection",
              "value": "keep-alive"
            }
          ],
          "queryString": [
            {
              "name": "userId",
              "value": "undefined"
            },
            {
              "name": "password",
              "value": "abc"
            }
          ],
          "cookies": [],
          "headersSize": 429,
          "bodySize": 0
        },
        "response": {
          "status": 200,
          "statusText": "OK",
          "httpVersion": "HTTP/1.1",
          "headers": [
            {
              "name": "Pragma",
              "value": "no-cache"
            },
            {
              "name": "Date",
              "value": "Thu, 02 Jun 2016 16:27:59 GMT"
            },
            {
              "name": "Server",
              "value": "Microsoft-IIS/8.0"
            },
            {
              "name": "X-AspNet-Version",
              "value": "4.0.30319"
            },
            {
              "name": "X-Powered-By",
              "value": "ASP.NET"
            },
            {
              "name": "Content-Type",
              "value": "application/json; charset=utf-8"
            },
            {
              "name": "Cache-Control",
              "value": "no-cache"
            },
            {
              "name": "X-SourceFiles",
              "value": "=?UTF-8?B?QzpcVXNlcnNca2lyXERlc2t0b3BcRSBEcml2ZVxXb3JrIExpdmVcTml0aW4gS0sgU29mdHdhcmVcVmlkZW9MaWJyYXJ5XHByb2plY3RcVmlkZW9MSWJyYXJ5XFZpZGVvTElicmFyeVxhcGlcdXNlclxsb2dpbg==?="
            },
            {
              "name": "Content-Length",
              "value": "46"
            },
            {
              "name": "Expires",
              "value": "-1"
            }
          ],
          "cookies": [],
          "content": {
            "size": 0,
            "mimeType": "application/json",
            "compression": 447,
            "text": ""
          },
          "redirectURL": "",
          "headersSize": 447,
          "bodySize": -447,
          "_transferSize": 0,
          "_error": ""
        },
        "cache": {},
        "timings": {
          "blocked": 2.24999990314245,
          "dns": -1,
          "connect": -1,
          "send": 0.19500008784235012,
          "wait": 22.8659999556839,
          "receive": 0.6709999870509336,
          "ssl": -1
        },
        "serverIPAddress": "[::1]",
        "connection": "15008"
      }
    ]
  }
}
在浏览器中显示相同结果的点击次数


正如kk和rick已经指出的,您不需要创建另一个承诺,因为
$http.get
已经返回了一个承诺。您还应该使用
然后
,而不是
成功/失败

所以你想要的应该是这样的:

function getData() {
  return $http.get('path-to-api/api.json').then( 
    function success(result) {
      // Do stuff with it
      return result.data;
    },
    function failure(err) {
      return err;
    });
}
注意,这将调用放在服务中,并从该服务返回对象中的函数

编辑 由于注释包含URL,我将添加以下内容作为编辑: 因此,从角度看,您点击的url是:
或者是

@Katana24我不知道如何感谢你,但你让我得到了这个答案。。。非常感谢

原因

Asp.net web api不允许跨源请求,除非您在
web.config
文件中添加
Access Control allow origin
。我做了
*
,所以从任何来源都可以访问APIes

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>


使用Firebug、Chrome Developer Tools或Fiddler查看HTTP上发生的事情,这将真正帮助您解决问题。尝试传递一个空对象,而不是空字符串<代码>数据:{}
顺便说一句,
$http
已经返回了一个承诺,不需要再做一个承诺。只是一个建议,$http已经返回了一个承诺。你不需要包装它,我知道
$http
会返回一个承诺..我的错。但问题是,当状态为200OK时,为什么会出现值为
null
的错误?API返回的数据在哪里。我可以在任何web浏览器中的Postman和简单http请求中获取数据,URL是否与您发布的URL完全相同?我还建议在上面返回的函数中插入一个断点/调试器,以查看它是否到达该点,然后检查对象,以查看您的数据是否确实存在。如果不是,并且响应正常,那么您可能没有从apierrorr
{“data”:null,“status”:-1,“config”:{“method”:“GET”,“transformRequest”:[null],“transformResponse”:[null],“url”:http://localhost:62158/api/user/login?userId=undefined&password=asfd,“headers”:{“Accept”:“application/json,text/plain,*/*”},“statusText”:“}
响应
请求URL:http://localhost:62158/api/user/login?userId=undefined&password=asdf 请求方法:获取状态代码:200 OK远程地址:[:::1]:62158在浏览器中打印相同的点击{Code:“成功”,消息:“有效用户”。}
我知道我可以重构代码。我为我的错误道歉。然而,我在这里发布的问题是为什么$http无法获取数据。先生,实际上,出于测试目的,我总是返回状态200OK,我单击了您在编辑中提供的两个URL,它们都工作正常并打印
{code:“成功”,消息:“Valid User.”}
干得好-如果您可以点击服务器,但没有看到任何数据,那么服务器端一定出了问题。很高兴你找到了解决办法。我接受现金;)哈哈