将[FromBody]应用程序/ x-www-form-urlencoded表单数据转换为ASP.NET WebAPI上的对象

时间:2018-08-29 22:09:09

标签: c# asp.net angular asp.net-web-api angular6

我从Angular 6 UI中发布了一个对象,我能够以字符串形式获取表单主体中的RAW数据。数据也到达了控制器方法。但是我无法将其投射到对象上

角度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";
}

将名为response的API重新获得为“ Receiveved 200 ok”。但是我所需要做的就是将表单数据解析为我的CalenderSchedulesModel对象。

请找到此API调用的请求标头

enter image description here

编辑:更改为HttpParams而不是发送表单数据

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

现在我得到了对象,但仍然无法解析为C#对象

enter image description here

0 个答案:

没有答案