1

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)?

2
  • 1
    Your ionic app isn't actually sending anything. If you want to send some data in the body of your request then GET is 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 to POST or PUT instead Commented Oct 28, 2017 at 17:21
  • Thank you, I have done a lot of modification to the code and now it's working. Commented Oct 28, 2017 at 23:51

1 Answer 1

2

After a lot of digging and modifications, I have finally got the API to work fine. In case someone ran into a problem similar to mine, Here what I did:-

  1. At Ionic, I have changed the HTTP request from GET to POST.

    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) => { ... });}
    
  2. At Backend, Used newtonsoft (JObject) Which saved me a lot of head that JsonResult causes, Then Changed Method type to 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);
        }
    
    }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.