C# 将[FromBody]应用程序/x-www-form-urlencoded表单数据转换为ASP.NET WebAPI上的对象
我从Angular 6 UI发布了一个对象,我能够以字符串的形式获取表单体中的原始数据。数据也到达控制器方法。但我无法将它投射到物体上 角度6-日历.Service.tsC# 将[FromBody]应用程序/x-www-form-urlencoded表单数据转换为ASP.NET WebAPI上的对象,c#,asp.net,angular,asp.net-web-api,angular6,C#,Asp.net,Angular,Asp.net Web Api,Angular6,我从Angular 6 UI发布了一个对象,我能够以字符串的形式获取表单体中的原始数据。数据也到达控制器方法。但我无法将它投射到物体上 角度6-日历.Service.ts saveSchedules(): Observable<any> { const sch: CalenderSchedulesModel = {ScheduleDate: 'today', description: 'all is well'}; const formData = new FormDat
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))));
}
现在我得到了object,但仍然无法解析为C#object
你能添加并查看它的工作情况吗?@Win我试过了。它仍然不能工作。我尝试在httpParams而不是formdata中设置它,这没有多大区别我认为您需要像这样将单个项作为键值对进行追加-
formdata.append('item1',value1')代码>@Win可以工作,但我的目的是在将来发送对象数组。如果我发送了一个对象,我就开始得到这个问题。我改变了const body=new-HttpParams().set('CalenderSchedulesModel',JSON.stringify(sch));我能够看到这个物体,但没有看到编码的数据。
[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";
}
const sch: CalenderSchedulesModel = {ScheduleDate: 'today', description: 'all is well'};
const body = new HttpParams().set('CalenderSchedulesModel', JSON.stringify(sch));