【问题标题】:$http request with angularjs is returning my html doc带有 angularjs 的 $http 请求正在返回我的 html 文档
【发布时间】:2014-08-23 10:29:57
【问题描述】:

我是新来的,如果我在帖子中犯了一些错误,请见谅...

我正在尝试将 angularjs 与 ASP.NET Web 窗体一起使用,在我需要向 c# webmethods 发出请求之前,一切都很顺利。我在这里和其他页面上搜索了解决方案,但没有找到任何东西。

让我们来解决问题:我的请求只返回我的 Default.aspx html 代码,而不是我的 JSON。事实上,我的请求并没有调用我的 webmethod...

app.controller('CtrlBoletos',function($scope, FactoryBoleto) {

    $scope.selections = [];

    $scope.boletos =  FactoryBoleto.getBoletos();

    $scope.gridBoletos = {
        data: 'boletos',
        selectedItems: $scope.selections,
        multiSelect: false
    };
});


app.factory('FactoryBoleto', function ($http) {

   var getBoletos = function() {

        $http({
           method: 'POST',
           url: "./Default.aspx/get_boleto",
           async: false
        }).success(function(result){
           console.info(result);
        });
   };
   return { getBoletos: getBoletos };
});

这是我的网络方法

[WebMethod]
 public static string get_boleto()
{     
    List<TFechamento_Boleto> lista = new List<TFechamento_Boleto>();
    JavaScriptSerializer serializer =new JavaScriptSerializer();
    TFechamento fechamento = new TFechamento(2);
    lista = fechamento.getDados(1).Boleto;

    var json = serializer.Serialize(lista);
    return json;

}

啊,如果我使用 JQuery AJAX 发出请求,我会得到 json...

谁来帮帮我,我快被这个弄疯了……对不起我的英语不好:p

【问题讨论】:

  • 旁注:这里有葡萄牙语版本的堆栈:pt.stackoverflow.com
  • 您可以在浏览器(Chrome、IE 或 Firefox)中使用开发者工具 (F12) 并检查这两个请求以查看您缺少的内容,正如您所说的可以使用 jQuery 请求。
  • 我做到了,请求是一样的,我用firebug来查看它们...已经从$http请求中更改了标头,使它们相等并且不起作用......@塞尔吉奥加西亚

标签: c# javascript asp.net angularjs


【解决方案1】:

我已通过设置标头、responseType 和添加空数据对象解决了这个问题

factory.handshake = function () {
    return $http({
        method: "POST",
        url: urlBase.concat("/Handshake"),
        data: {},
        headers: { "Content-Type": "application/json" },
        responseType: 'json'
    });
};

...而且,当我调用我的 webmethod 时,结果神奇地出现了

    myFactory.handshake()
        .success(function (fromApi) {
            alert(fromApi.d);
        })
        .error(function (error) {
            $scope.status = 'Unable to load sport data: ' + error.message;
        });

【讨论】:

    【解决方案2】:

    你是否缺少 [ScriptMethod(UseHttpGet = true)] ?

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public List<ProjectOfEmployee> GetAllProjectName()
    {
       return GetProjectName();   
    }
    

    http://shahjadatalukdar.wordpress.com/2013/08/09/how-to-call-asmx-webservice-using-http-get- with-jquery-ajax/

    检查,其他一些线程:

    https://groups.google.com/forum/#!msg/angular/AQ_caU-qVJ0/Csugs6zI2-EJ

    AngularJS call webmethod

    【讨论】:

    • 没用,请求的结果还是html页面... :(
    【解决方案3】:

    出于好奇/学习 Angular,我对此进行了修改:

    问题是 content-type 标头 - if you don't define this, the WebMethod isn't invoked,您将获得 aspx 页面(实际上在 jQuery 和 Angular..any 中)

    ASP.NET AJAX 内容类型标头验证

    ASP.NET 为基于 GET 和 POST 的 ASP.NET AJAX Web 方法强制实施了一个内置的保护验证层,即无论使用什么 HTTP 动词,ASP.NET 始终要求HTTP Content-Type 标头设置为值 application/json如果不发送此内容类型标头,ASP.NET AJAX 将拒绝服务器上的请求。

    所以试试这个,不是真的发送任何数据,但 Angular 会设置标题:

    $http.post("default.aspx/get_boleto", {});
    

    或者在你的情况下:

     $http({
           method: 'POST',
           url: "./Default.aspx/get_boleto",
           data: {}, //nothing really, just doing this so the header is set
           async: false
        }).success(.....
    

    如果您检查您的 XHR 调用:

    Angular XHR 没有数据,Content-Type 没有设置:

    POST /default.aspx/helloWorld HTTP/1.1
    Host: localhost:51120
    Connection: keep-alive
    Content-Length: 0
    Cache-Control: max-age=0
    Accept: application/json, text/plain, */*
    Origin: http://localhost:51120
    User-Agent: ....
    Referer: ....
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: en-US,en;q=0.8
    

    Angular XHR 带有数据,Content-Type 设置:

    POST /default.aspx/helloWorld HTTP/1.1
    Host: localhost:51120
    Connection: keep-alive
    Content-Length: 2
    Cache-Control: max-age=0
    Accept: application/json, text/plain, */*
    Origin: http://localhost:51120
    User-Agent:...
    Content-Type: application/json;charset=UTF-8
    Referer: ....
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: en-US,en;q=0.8
    

    Angular 的新手,所以如果有更好/更简单的方法,我会推迟...

    第...

    【讨论】:

      【解决方案4】:

      我和你有同样的问题。直到现在我已经创建了一个替代解决方案来从我的 c# webmethod 获取 json 结果:

       $scope.yourscopefunction=function(){
               $.ajax({
                              type: "POST",
                              url: "webmethodURL",                       
                              contentType: "application/json;charset=utf-8",
                              success: function (data) {
      
                                  $.map(data.d, function (dataobject) {
      
                                    alert(dataobject.yourobjectfield);
      
                                  });
      
                              },
                              error: function (xhr, status, errorThrown) {
      
                                  alert(status + "* " + errorThrown + " * " + xhr);
                              }
                          });
      
       };
      

      如果你有比这更好的使用 $http 的解决方案,请告诉我

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-15
        • 1970-01-01
        • 1970-01-01
        • 2015-07-02
        相关资源
        最近更新 更多