我正在做一个小项目,用ASP WebAPI2学习Angular7。当我使用http.post()发布时,ASP Web API控制器没有收到任何值,并且obj设置为null。
我试图在应用程序的其他部分中实现类似的代码,并且工作正常。
我的WebAPI看起来像这样-
[Route("api/rota/InsertRota")]
[HttpPost]
public HttpResponseMessage InsertRota(Models.HelpdeskStaffRota paraStaffRota)
{
try
{
string conString = ConfigurationManager.ConnectionStrings["HelpdeskStaffRota"].ConnectionString;
using (SqlConnection conn = new SqlConnection(conString))
using (SqlCommand comm = new SqlCommand("RotaInsert", conn))
{
conn.Open();
comm.CommandType = System.Data.CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@RotaDate", paraStaffRota.RotaDate));
comm.Parameters.Add(new SqlParameter("@RotaMorning", paraStaffRota.RotaMorning));
comm.Parameters.Add(new SqlParameter("@RotaLunch", paraStaffRota.RotaLunch));
comm.Parameters.Add(new SqlParameter("@RotaLate", paraStaffRota.RotaLate));
comm.ExecuteNonQuery();
conn.Close();
}
List<Models.HelpdeskStaffRota> items = GetItems();
return Request.CreateResponse(HttpStatusCode.OK, items);
}
catch (System.Exception e)
{ return Request.CreateResponse(HttpStatusCode.SeeOther, e.Message); }
}
和asp模型-
public class HelpdeskStaffRota
{
public Int64 Id { get; set; }
[Required(ErrorMessage = "Please select a date")]
public DateTime RotaDate { get; set; }
[Required(ErrorMessage = "Please select a Staff for Morning")]
public string RotaMorning { get; set; }
[Required(ErrorMessage = "Please select a Staff for Lunch")]
public string RotaLunch { get; set; }
[Required(ErrorMessage = "Please select a Staff for Late")]
public string RotaLate { get; set; }
public string RotaDateString {
get
{
return this.RotaDate.ToString("dd/MM/yyyy");
}
set
{
this.RotaDate = DateTime.ParseExact(value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
}
}
和Angular服务-
addRota(rota: Rota) {
const addRotaURL = `${this.baseURL}api/rota/InsertRota`;
return this.http.post(addRotaURL, rota);
}
和Angluar Rota类-
export class Rota {
Id: number;
RotaDate: Date;
RotaMorning: string;
RotaLunch: string;
RotaLate: string;
}
如果我进入调试模式,则可以看到角度代码确实设置了对象值,并且可以看到它碰到了控制器内部的断点,但是paraStaffRota的值为null。我的期望是paraStaffRota(web api controller)= rota(从角度发布)。
任何帮助将不胜感激。
对于那些正在寻找一种更好的方法的人-
我认为使用自定义日期适配器将是一种更好,更干净的方法。我做了以下。
import { Injectable } from '@angular/core';
import { NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
@Injectable({
providedIn: 'root'
})
export class DateStringService {
constructor() { }
fromModel(value: string): NgbDateStruct {
if (!value) {
return;
}
let segments = value.split('-');
let dateObj = {
year: Number(segments[0]),
month: Number(segments[1]),
day: Number(segments[2])
};
return dateObj;
}
toModel(date: NgbDateStruct): string {
if (!date) {
return;
}
return `${date.year}-${date.month}-${date.day}`;
}
}
然后在app.module.ts-中使用它
providers: [
{ provide: NgbDateAdapter, useClass: DateStringService }
],
而已。就行了!您无需在其他任何地方进行任何更改。Angular将从这里开始。它对我有用,我发现这种方法比以前的方法更好,更干净。希望能有所帮助。如果您遇到更好的解决方案,请在此处分享。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句