0

I'm posting an Object from Angular 6 UI, I'm able to get the RAW data in form body as string. The data reached to controller method too. But I was not able to cast it to an object

Angular 6 - calendar.Service.ts

saveSchedules():  Observable<any> {
 const sch: CalenderSchedulesModel = {ScheduleDate: 'today', description: 'all is well'};
    const formData = new FormData();
    formData.append('CalenderSchedulesModel', JSON.stringify(sch));
    const postOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
      }),
      withCredentials: true,
    };

   return this.http.post('http://mydevserver.com/api/schedules',
   formData,
   postOptions)
  .pipe(catchError(this.handleError.bind(this)))
  .pipe(map(data =>console.log(JSON.stringify(data))));

}

ASP.NET WebAPI - CalenderController.cs

[HttpPost]
public async System.Threading.Tasks.Task<String> schedules(CalenderSchedulesModel CalenderSchedulesModel)
{
    try { 
        string content = "";            
        if (ModelState.IsValid && CalenderSchedulesModel != null)
        {
            //  This if block is passed     
            Logger.Info("CalenderSchedulesModel.ScheduleDate); //prints null
            Logger.Info(HttpUtility.HtmlEncode(CalenderSchedulesModel.ScheduleDate)); //prints null                 
            using (var contentStream = await this.Request.Content.ReadAsStreamAsync())
            {
                contentStream.Seek(0, SeekOrigin.Begin);
                using (var sr = new StreamReader(contentStream))
                {
                    content = sr.ReadToEnd();                        
                    Logger.Info(content); // prints ------WebKitFormBoundaryomeguzqYBNNqAAyg information with {"ScheduleDate":"today","description":"all is well"}
                }
            }
        }   
    }
    catch (Exception e)
    {
        Logger.Error(e.Message);
        Logger.Error(e.ToString);
        Logger.Error(e.StackTrace);
    }
    return "Recieved 200 ok";
}

after the API called response is reieved as "Recieved 200 ok" . But All i need is to parsing the form data to my CalenderSchedulesModel object.

Please find the request header for this API Call

enter image description here

EDIT: Changed to HttpParams instead of sending form data

const sch: CalenderSchedulesModel = {ScheduleDate: 'today', description: 'all is well'};
    const body = new HttpParams().set('CalenderSchedulesModel', JSON.stringify(sch));

Now I get object but still can't parse to C# object

enter image description here

Karthick Radhakrishnan
  • 1,151
  • 3
  • 12
  • 32
  • Could you add [FromBody](https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api#using-frombody) and see it work? – Win Aug 29 '18 at 22:43
  • @Win I tried that..It won't work still. I tried setting it in httpParams instead of formdata, it doesn't make much difference – Karthick Radhakrishnan Aug 29 '18 at 22:59
  • I believe you need to append individual item as key-value pair like this - `formData.append('item1', 'value1');` – Win Aug 29 '18 at 23:11
  • @Win That works, but my intention is to send Array of objects in future. if i send an object I start getting this issue – Karthick Radhakrishnan Aug 29 '18 at 23:20
  • Now I Changed const body = new HttpParams().set('CalenderSchedulesModel', JSON.stringify(sch)); I was able to see the object but sill encoded data. – Karthick Radhakrishnan Aug 29 '18 at 23:22
  • I think this is another chance to write a little bit of code and use a ModelBinder. https://stackoverflow.com/questions/52084903/asp-net-web-api-modelbinder-single-parameter/52087361#52087361 – No Refunds No Returns Aug 30 '18 at 01:07

0 Answers0