#c# #asp.net #post #angular
#c# #asp.net #Публикация #angular
Вопрос:
Я использую Angular 2 и ASP.Net MVC. При отправке данных (метод getData) на сервер получают значение null. Для теста я попытался отправить post-запрос с помощью jquery ajax, все прошло хорошо. Пожалуйста, скажите мне, в чем проблема?
properties.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import '../../../shared/rxjs-operators';
import { PropertyNode } from './property.model';
@Injectable()
export class PropertiesService {
private headers = new Headers({ 'Content-Type': 'application/json' });
private dataUrl = 'Editor/returnProperties';
constructor(private http: Http) { }
getData(FullName: string): Promise<PropertyNode[]> {
let body = JSON.stringify({ FullName: FullName});
let options = new RequestOptions({
headers: this.headers
});
return this.http.post(this.dataUrl, body, this.headers)
.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);
}
}
EditorController.cs
[HttpPost]
public JsonResult returnProperties(string FullName)
{
try
{
PAVBaseDataItem node = IDE.MvcApplication.fDataProvider.RootItem.ChildItem(FullName);
List<PAVBasePropertyItem> properties = node.PropertiesList();
return Json(properties);
}
catch (Exception ex)
{
return Json("");
}
}
Скриншот c # debug,
Скриншот 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);
}
Ответ №1:
Обновите код вашего контроллера
[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("");
}
}
По умолчанию из тела разрешаются только сложные параметры.
Комментарии:
1. Привет, скажите, пожалуйста, пространство имен для [FormBody]?
2.
System.Web.Http
3. Исправлено, как в вашем примере, но на сервере получают null.
4. Можете ли вы проверить в консоли разработчика, действительно ли добавлено тело ваших запросов и что внутри?
5. Точка останова перехватывает запрос, но я не вижу ее значения в консоли visual studio.
Ответ №2:
Попробуйте что-то вроде этого
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 = resu<
},
err => console.log(err)
);
Ответ №3:
Изменил 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);
}
}