简体   繁体   English

带有angularjs的$ http请求正在返回我的html doc

[英]$http request with angularjs is returning my html doc

I'm new here, so sorry if I'm making some mistake with the post... 我是新来的,很抱歉,如果我在帖子上犯了一些错误......

I'm trying to use angularjs with ASP.NET Web Forms, and everything was going well until I need to make a request to the c# webmethods. 我正在尝试将angularjs与ASP.NET Web Forms一起使用,一切顺利,直到我需要向c#webmethods发出请求。 I searched here and on other pages for the solution and didnt found anything. 我在这里和其他页面上搜索解决方案并没有找到任何东西。

Let's go to te problem: My request just return my Default.aspx html code, and not my JSON. 让我们来解决问题:我的请求只返回我的Default.aspx html代码,而不是我的JSON。 In fact, my request doesn't call my webmethod... 事实上,我的请求不会调用我的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 };
});

and this is my webmethod 这是我的webmethod

[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;

}

Ah, and if i make the request with JQuery AJAX I get the json... 啊,如果我用JQuery AJAX发出请求,我会得到json ...

someone help me, im getting crazy with this... and sorry for my bad english :p 有人帮助我,我对此感到疯狂......对不起我的坏英语:p

I've resolved this issue by setting headers, responseType and by adding an empty data object 我通过设置头文件,responseType和添加一个空数据对象来解决这个问题

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

...and, when I call my webmethod the result magically appears ......而且,当我打电话给我的网络方法时,结果会神奇地出现

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

Are you missing [ScriptMethod(UseHttpGet = true)] ? 你错过了[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/ http://shahjadatalukdar.wordpress.com/2013/08/09/how-to-call-asmx-webservice-using-http-get-with-jquery-ajax /

Checking, some others threads: 检查,其他一些线程:

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

AngularJS call webmethod AngularJS调用webmethod

i have the same problem as you.until now i have create an alternative solution to get json result from my c# webmethod: 我和你有同样的问题。现在我已经创建了一个替代解决方案来从我的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);
                        }
                    });

 };

if you have an other solution better than this using $http, please tell me 如果您使用$ http有更好的解决方案,请告诉我

I tinkered with this out of curiosity/learning Angular: 出于好奇/学习Angular,我对此进行了修改:

The issue is content-type header - if you don't define this, the WebMethod isn't invoked and you will get the aspx page (in both jQuery and Angular..any actually) 问题是content-type标题 - 如果你没有定义它,不调用WebMethod你会获得aspx页面(在jQuery和Angular中实际上都是)

ASP.NET AJAX Content-Type Header Validation ASP.NET AJAX内容类型标头验证

There is a built-in validation layer of protection that ASP.NET enforces for both GET and POST based ASP.NET AJAX web methods, which is that regardless of the HTTP verb being used, ASP.NET always requires that the HTTP Content-Type header is set to the value application/json . ASP.NET强制执行基于GET和POST的ASP.NET AJAX Web方法的内置验证保护层,无论使用何种HTTP动词, ASP.NET始终要求HTTP Content-Type header设置为值application / json If this content type header is not sent, ASP.NET AJAX will reject the request on the server. 如果未发送此内容类型标头,ASP.NET AJAX将拒绝服务器上的请求。

So try this, not really sending any data, but Angular will set the header: 所以尝试这个,而不是真正发送任何数据,但Angular将设置标题:

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

or in your case: 或者在你的情况下:

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

If you inspect your XHR call: 如果您检查XHR呼叫:

Angular XHR without data, Content-Type isn't set: 没有数据的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 with data, Content-Type is set: 数据 ,角度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

New at Angular so if there are better/easier ways, I'll defer... Angular的新功能,如果有更好/更简单的方法,我会推迟......

Hth... 心连心...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 返回已执行JS的HTML文档 - Returning HTML Doc with JS Already Executed 准备 controller 和 http 请求以处理请求而不返回值 - Prepare controller and http request to preocess request without returning value http状态代码200返回预期结果。 但是,当状态为BadRequest或未经授权时,我的C#webapi 1返回text / html - http status code 200 returns expected result. But when status is BadRequest or Unauthorized, my C# webapi 1 is returning text/html 从HTTP请求中删除HTML节点 - Remove HTML nodes from HTTP Request HTTP请求以C#获取HTML代码 - HTTP Request to get HTML code in C# 我的 lambda function 没有返回错误请求 - My lambda function is not returning bad request 在 WebAPI 和 AngularJS 中出现错误:“未找到与请求 URI 匹配的 HTTP 资源” - Getting the error: “No HTTP resource was found that matches the request URI” in WebAPI and AngularJS HTTP DELETE请求返回(405)方法不允许错误。 为什么? - HTTP DELETE Request returning a (405) Method Not Allowed Error. Why? C#HTTP GET请求返回隐藏字符 - C# HTTP GET request returning hidden characters HTTP Web请求未返回C#中预期的结果 - HTTP web request not returning what is expected in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM