草庐IT

javascript - Angularjs $http.post - 将参数作为 JSON 发送到 ASPX webmethod

coder 2025-04-01 原文

我有以下 angularjs 代码将 http post 发送到 webmethod,但我收到以下错误,没有更多信息。有人可以帮忙吗? 如果我不向 webmethod 发送任何数据而只从中获取数据,它就可以正常工作!

无法加载资源:服务器响应状态为 500(内部服务器错误) angular.js:11442 POST http://localhost:54461/GetData.aspx/getData 500(内部服务器错误)

Javascript:

var request = "{'name':'" + "Nariman" + "'age':'" + 12 + "'}";
$scope.retData = {};

var config = {
    headers: {
        'Content-Type': '"application/json; charset=utf-8";',
        'dataType': '"json"'
    }
}

$scope.retData.getResult = function (item, event) {

    $http.post('GetData.aspx/getData', request, config)
        .success(function (data, status, headers, config) {
            $scope.retData.result = data.d;
        })
        .error(function (data, status, headers, config) {
            $scope.status = status;
        });
}

ASPX 网络方法(C#):

public static string getData(string name, int age)
{
    string.Format("Name: {0}{2}Age: {1}", name, age, Environment.NewLine);
}

编辑 ------------------------------------

如果我不向网络方法发送任何 json 数据,它就可以正常工作。例如,下面的代码有效,如果我在 web 方法中放置断点,它会显示它在那里。但是如果我发送 json 数据,它不会进入 webmethod:

Javaacript(不发送任何 json 数据):

var config = {
    headers: {
        'Content-Type': '"application/json; charset=utf-8";',
        'dataType': '"json"'
    }
}

$scope.retData.getResult = function(item, event) {
    $http.post('GetData.aspx/getData', data, config)
        .success(function(data, status, headers, config) {
            $scope.retData.result = data.d;
        })
        .error(function(data, status, headers, config) {
            $scope.status = status;
        });
}

ASPX(没有输入参数时)

public static string getData()
{
    // just having a breakpoint shows it comes inside the 
    // webmethod when no data is passed. 
}

最佳答案

您的问题似乎与 Emmanual Durai 在您问题的第一条评论中指出的一样:var request = "{'name':'"+ "Nariman"+ "'age':'"+ 12 + "'}"; 不是有效的 json 对象。

request 会给你 {'name':'Nariman'age':'12'} 作为字符串,它不会解析为 JSON(有问题格式)。

你应该尝试像下面这样的东西来获得一个有效的字符串

var request = {
    name: "Nariman",
    age: 12
}

var requestString = JSON.stringify(request)

也请看这里How to pass json POST data to Web API method as object .您的问题通常不是特定于 angularjs $http,而是通常针对 XHR 请求。

关于javascript - Angularjs $http.post - 将参数作为 JSON 发送到 ASPX webmethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36203610/

有关javascript - Angularjs $http.post - 将参数作为 JSON 发送到 ASPX webmethod的更多相关文章

  1. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  2. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  3. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou

  4. ruby-on-rails - rails : How to make a form post to another controller action - 2

    我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak

  5. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  6. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  7. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  8. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  9. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  10. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

随机推荐