2017-10-28 45 views
1

我有一個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(數據或錯誤)的正確方法是什麼?

+1

你離子的應用程序實際上不發送任何數據。如果你想在你的請求中發送一些數據,那麼'GET'是錯誤的請求類型。您應該在GET請求中包含參數到您的URL中(例如'http://example.com/api/Authentication?id = 1'),或者對於具有JSON主體的請求,切換到'POST'或'PUT '而不是 –

+0

謝謝,我對代碼做了很多修改,現在它正在工作。 – Kuma

回答

1

經過大量的挖掘和修改,我終於得到了API的正常工作。 萬一有人跑進我相似的問題,在這裏我做了什麼: -

  1. 在離子,我已經改變了從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) => { ... });} 
    
  2. 在後端,使用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); 
        } 
    
    }