ASP.NET Core 2.0 Web API从离子3接收/发送Json请求3
问题描述:
我有一个ASP.NET Core 2.0 Web API与离子3集成在一起。 我在接收离子3应用程序发送的JSON数据时出现问题,这里是示例代码: -ASP.NET Core 2.0 Web API从离子3接收/发送Json请求3
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { AlertController, LoadingController } from 'ionic-angular';
import { FCM } from '@ionic-native/fcm';
@Injectable()
export class ServerProvider {
private baseurl = "http://localhost:9681/api";
private api: String[] = new Array();
public loader: any;
constructor(public fcm: FCM, public http: Http, public alertCtrl:
AlertController, public loadingCtrl: LoadingController) {
this.api['auth'] = 'Authentication';
this.api['agency'] = 'Agencies';
this.api['user'] = 'Users';
this.api['route'] = 'Routes';
this.api['token'] = 'Tokens';
this.api['notification'] = 'Notifications';
this.api['salepoint'] = 'Salepoints';
}
ServerRequest(api, request, data) {
return new Promise((resolve) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json; charset=UTF-8');
this.http.get(this.baseurl + "/" + this.api[api] + "/", {headers: headers}).map(res => res.json()).subscribe((result) => {
resolve(result);
console.log(result);
}, (error) => {
console.log(error); this.CreateAlert("Error", error, [
{
text: 'Close',
handler:() => {
this.loader.dismiss();
}
}
]);
},() => {
this.loader.dismiss();
});
});
}
后端: -
[Route("api/Authentication")]
public class AuthenticationController : Controller
{
IConfiguration _configuration;
public AuthenticationController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet]
public JsonResult GetUser(JsonResult json)
{
AgencyUsers agencyusers = new AgencyUsers(_configuration);
return Json(agencyusers.GetUser(json));
}
}
我收到以下错误: -
An unhandled exception occurred while processing the request. InvalidOperationException: Could not create an instance of type 'Microsoft.AspNetCore.Mvc.JsonResult'. Model bound complex types must not be abstract or value types and must have a parameterless constructor.
接收(序列化和反序列化JSON)并发回JSON(数据或错误)的正确方法是什么?
答
经过大量的挖掘和修改,我终于得到了API的正常工作。 万一有人跑进我相似的问题,在这里我做了什么: -
-
在离子,我已经改变了从GET到POST HTTP请求。
ServerRequest(api, request, data) { return new Promise((resolve) => { let headers = new Headers(); headers.append('Content-Type', 'application/json; charset=UTF-8'); this.http.post(this.baseurl + "/" + this.api[api] + "/" + request, JSON.stringify(data),{headers:headers}).map(res => res.json()).subscribe((result) => { ... });}
-
在后端,使用newtonsoft(JObject)这救了我很多头JsonResult引起的,则改为方法类型IActionResult。
[HttpPost("GetAgencyUser")] public IActionResult GetAgencyUser([FromBody]JObject request) { try { if (request["id"] == null) { return Ok("id is not defined or incorrect JSON format"); } AgencyUsersMethods agencyusers = new AgencyUsersMethods(_configuration); var result = agencyusers.GetAgencyUser(request); if (result == null) { return Ok("User not Found"); } else { return Ok(result); } } catch (Exception ex) { return BadRequest(ex.Message); } }
你离子的应用程序实际上不发送任何数据。如果你想在你的请求中发送一些数据,那么'GET'是错误的请求类型。您应该在GET请求中包含参数到您的URL中(例如'http://example.com/api/Authentication?id = 1'),或者对于具有JSON主体的请求,切换到'POST'或'PUT '而不是 –
谢谢,我对代码做了很多修改,现在它正在工作。 – Kuma