Jones
Jones

Reputation: 217

Asp.NetCore API Controller not getting Data from Json

I have 2 applications, one which posts data to another. When I run the first application the post method in the controller executes but the model or ObjavaDto (objaveList) can't be found so it's null. When I copy-paste the json from var json into Postman everything works. What am I missing?

var json = new JavaScriptSerializer().Serialize(objaveList[2]); 

I used [2] just for simplicity reasons because there are a lot of them

string url = "http://localhost:61837/api/Objave";

string result;
using (var client = new WebClient())
      {
         client.Headers.Add("Content-Type", "application/json");
         result = client.UploadString(url, "POST", json);
      }

2nd application Controller

namespace StecajeviInfo.Controllers.Api
{
     [Route("api/[controller]")]
     public class ObjaveController : Controller
     {  

       [HttpPost]
       public void Post([FromBody]ObjavaDto objaveList)
       {

       } 

     }
}
public class ObjavaDto
{
    public string OznakaSpisa { get; set; }
    public string NazivOtpravka { get; set; }
    public string NazivStecajnogDuznika { get; set; }
    public string PrebivalisteStecajnogDuznika { get; set; }
    public string SjedisteStecajnogDuznika { get; set; }
    public string OIBStecajnogDuznika { get; set; }
    public string OglasSeOdnosiNa { get; set; }
    public DateTime DatumObjave { get; set; }
    public string OibPrimatelja { get; set; }
    public string Dokument { get; set; }
}    

Sent data looks like this

{
    "OznakaSpisa":"St-6721/2015",
    "NazivOtpravka":"Rješenje - otvaranje stečajnog postupka St-6721/2015-7",
    "NazivStecajnogDuznika":"RAIN AIR d.o.o.",
    "PrebivalisteStecajnogDuznika":"Savska 144/A, 10000, Zagreb",
    "SjedisteStecajnogDuznika":"",
    "OIBStecajnogDuznika":‌​"37144498637",
    "Oglas‌​SeOdnosiNa":"Missing Oib",
    "DatumObjave":"\/Date(1501106400000)\/",
    "OibPrimatelja"‌​:"37144498637",
    "Doku‌​ment":"e-oglasna.pra‌​vosudje.hr/sites/def‌​ault/files/ts-zg-st/‌​…;"
}

Upvotes: 0

Views: 460

Answers (2)

Jones
Jones

Reputation: 217

Thank you all for your replies, you have been very helpful and gave me an idea how to test. I tested with commenting out properties and I found out it's because of the special characters in Naziv otpravka ("Rješenje" and "stečajnog") which are luckily present only in that property.

I found that this solved the problem https://stackoverflow.com/a/12081747/6231007

client.Headers["Content-Type"] = "application/json; charset=utf-8";
client.UploadDataAsync(new Uri(url), "POST", 
Encoding.UTF8.GetBytes(json));

Upvotes: 1

tlt
tlt

Reputation: 15291

Datetime is problematic. Make it nullable (DateTime?) and test with that. You'll probably get all other properties filled and datetime will stay null. If that's the problem, make sure your client sends datetime format that your model binder understands.

Upvotes: 0

Related Questions