I have an ASP.NET Core 2.0 Web API Integrated with ionic 3. I'm having problems receiving JSON data sent from ionic 3 App, Here is sample code:-
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();
});
});
}
Backend:-
[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));
}
}
I receive the following error:-
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.
What is the correct way to receive (serialize and deserialize JSON) and send back JSON (data or errors)?
GETis the wrong type of request. You should either include the parameters in your URL for a GET request (e.g.http://example.com/api/Authentication?id=1) or for a request with a JSON body, switch toPOSTorPUTinstead