Angular 2 post data在asp.net MVC中是空的

本文关键字:MVC net asp post data Angular | 更新日期: 2023-09-27 18:14:25

我使用Angular 2和ASP。净MVC。当向服务器发送数据(getData方法)时,接收null。对于测试,我尝试使用jquery ajax发送一个post请求,一切都很顺利。请告诉我有什么问题?

<标题> properties.service.ts h1> EditorController.cs h1> 图c#调试截图chrome-devtools。

更新

修改了properties.service。ts,它工作了。getData方法中的所有更改:

getData(FullName: string): Promise<PropertyNode[]> {
        let body = JSON.stringify({ FullName });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post(this.dataUrl, body, options)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }

Angular 2 post data在asp.net MVC中是空的

更新控制器代码

[HttpPost]
public JsonResult returnProperties([FromBody]string FullName) // <--- Added FromBody
{
    try
    {
        PAVBaseDataItem node = IDE.MvcApplication.fDataProvider.RootItem.ChildItem(FullName);
        List<PAVBasePropertyItem> properties = node.PropertiesList();
        return Json(properties);
    }
    catch (Exception ex)
    {
    return Json("");
    }
} 

默认情况下,只有复杂参数才会从body中解析。

试试这样

   const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.post(this.dataUrl, JSON.stringify(data), { headers: headers })      //added return
        .map(response => response.json())
        .subscribe(result => {
            var returneddata = result;
        },
        err => console.log(err)
        );

修改了properties.service。ts,它工作了。getData方法中的所有更改:

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { PropertyNode } from './property.model';
@Injectable()
export class PropertiesService {
    private dataUrl = 'Editor/returnProperties';
    constructor(private http: Http) { }
    getData(FullName: string): Promise<PropertyNode[]> {
        let body = JSON.stringify({ FullName });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post(this.dataUrl, body, options)
            .toPromise()
            .then(this.extractData)
            .catch(this.handleError);
    }
    private extractData(res: Response): PropertyNode[] {
        let data = res.json();
        let properties: PropertyNode[] = [];
        console.log(data)
        return data;
    }
    private handleError(error: any) {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}