使用Angular 2调用ASP.Net Web方法

时间:2017-10-16 14:23:13

标签: c# angular webmethod

我似乎有一个简单的场景,但我无法让它工作......我有一个ASPX页面,后面有代码。我想在后面的代码中访问Web方法。为此,我在app.component.ts中添加了一个订阅者,该订阅者调用返回observable的服务。该服务应该调用我的Web方法。这是我的代码:

service.component.ts

import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';


@Injectable()
export class GetDataService {
headers: any;
constructor(private _http: Http) {

}

WebMethodExample(): Observable<string> {
    return this._http.get("Default.aspx/WebMethodExample").map(
        (response: Response) => response.toString()
    );
}
}

app.component.ts(订阅者)

import { Component, OnInit } from '@angular/core';
import { GetDataService } from './Components/service.component';

@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>`,
providers:[GetDataService]
})
export class AppComponent {
name = 'Angular 2 (From component)';

constructor(private _get:GetDataService) { }

ngOnInit(): void {
    console.log("In OnInit"); 
    this._get.WebMethodExample().subscribe((data) => console.log(data));
}
}

代码隐藏(Default.aspx.cs)

using System;
using System.Web.Services;


namespace Angular2Demo10
{
public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string WebMethodExample()
    {
        return "Sent from WebMethodExample";
    }
}
}

当我运行它时,我在控制台中得到以下内容:“响应状态:200 OK,URL:null”。我不确定为什么它没有获取URL。任何帮助表示赞赏。

编辑:依赖关系:

  "dependencies": {
"@angular/common": "~2.1.1",
"@angular/compiler": "~2.1.1",
"@angular/core": "~2.1.1",
"@angular/forms": "~2.1.1",
"@angular/http": "~2.1.1",
"@angular/platform-browser": "~2.1.1",
"@angular/platform-browser-dynamic": "~2.1.1",
"@angular/router": "~3.1.1",
"@angular/upgrade": "~2.1.1",
"bootstrap": "3.3.7",
"core-js": "^2.4.1",
"es5-shim": "^4.5.9",
"es6-shim": "^0.35.3",
"reflect-metadata": "^0.1.8",
"rxjs": "5.4.3",
"systemjs": "0.19.39",
"zone.js": "^0.6.25"

},

1 个答案:

答案 0 :(得分:2)

查看所有其他示例,您是否尝试过正确设置标头,并使用POST而不是GET(我知道这很奇怪)。

另请注意,我们使用.json代替.tostring

进行回复
WebMethodExample(): Observable<string> {

    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    var content = {};

    return this._http.post("Default.aspx/WebMethodExample",
    content, {
        headers: headers
      }).map(
        (response: Response) => response.json()
    );
}