【发布时间】:2020-02-07 14:39:06
【问题描述】:
我有一个对象类,我想在我的 ASP.NET Core Angular 项目中使用它。我无法通过 http get 方法映射对象返回。请问有什么选择吗?
类文件:
[Serializable]
public class PricesRules
{
public HashSet<Price> Prices { get; set; }
public HashSet<Customer> Customers { get; set; }
public HashSet<Payment> Payments { get; set; }
}
component.ts :
public prices: PricesRules;
constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {
http.get<PricesRules>(baseUrl + 'api/UpdatePrices/GetLastPrices').subscribe(result => {
this.prices = result[0];
}, error => console.error(error));
}
interface PricesRules {
Prices: any[];
Customers: any[];
Payments: any[];
}
控制器文件:
[HttpGet("[action]")]
public IEnumerable<PricesRules> GetLastPrices()
{
PricesRules pricesRules = null;
//some code here
yield return pricesRules;
}
在我的组件中,我的结果对象中有很好的值,但之后我的对象价格未定义。
编辑:现在 get 方法没问题,但我的 post 方法没有触发我的控制器。
组件.ts '''
onClickSubmit(data) {
const params = new HttpParams().set('ID', '1');
const headers = new HttpHeaders().set('content-type', 'application/json');
this.http.post<PricesRules>(this.baseUrl + 'api/UpdatePrices/PostUpdatePrices' + this.prices, { headers, params }).subscribe(result => {
console.log("success");
}, error => console.error(error));
} '''
控制器
'''
[HttpPost("[action]")]
public async Task<IActionResult> PostUpdatePrices([FromBody] PricesRules pricesRules)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return null;
}
'''
我有这个错误:
Object { headers: {…}, status: 404, statusText: "Not Found", url: "https://localhost:44374/api/UpdatePrices/PostUpdatePrices[object%20Object]", ok: false, name: "HttpErrorResponse", message: "Http failure response for https://localhost:44374/api/UpdatePrices/PostUpdatePrices[object%20Object] : 404 Not Found", 错误: "\n\n\n\nError\n\n\n
无法发布 /api/UpdatePrices/PostUpdatePrices%5Bobject%20Object%5D\n\n\n" }
【问题讨论】:
-
您正在从服务器返回一个
IEnumerable<PricesRules>,但在您的前端,您已经表明您的获取请求的返回值将只是PricesRules的一个实例@ 即http.get<PricesRules>。这可能是问题的原因? -
是的,我已经修改了它,但它仍然是一样的
标签: c# angular asp.net-core mapping http-get