【问题标题】:Data that is posted from angular 4 is getting as null in .net core web api从 Angular 4 发布的数据在 .net core web api 中为空
【发布时间】:2018-05-24 07:12:12
【问题描述】:

作为学习的一部分,我正在创建一个角度表单并将其连接到 Web api,当我从表单发布数据时,它在 api 中作为空值获取,我尝试添加一个 [Route("jsonbody ")] 但那不起作用,也在服务中尝试了JSON.stringify(model) 但那也不起作用。

这就是我从角度发布数据的方式

onSubmit(form: NgForm) {
   this.registerobj.postUserData(this.model).subscribe()
 }

模型类是

export class UserModel {
constructor(
    public FirstName: string ='',
    public LastName: string = '',
    public Address: string = '',
    public DateOfBirth: string = '',
    public Gender: string = '',
    public Language: string = '',
    public Email: string = ''
) {}
}

这样发布服务中的数据

postUserData(model: UserModel) {
     return this.http.post<any>(`${this.serviceUrl}`, model)
}

.Net Core api 控制器

[Route("api/[controller]")]
    public class UserController : Controller
    {
        public UserController(IUser userItems)
        {
            UserItems = userItems;
        }
        public IUser UserItems { get; set; }

        [HttpPost]
        public IActionResult Insert(UserModel user)
        {
            UserRepository UserItems = new UserRepository();
            try
            {

                if (user == null)
                {
                    return BadRequest("Recieved a Bad request");
                }
              UserItems.Add(user);

               return Ok();
            }
            catch(Exception e)
            {
                return StatusCode(500, e);
            }

        }
    }

API 中的用户模型

 public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string DateOfBirth { get; set; }
    public string Gender { get; set; }
    public string Language { get; set; }
    public string Email { get; set; }
}

【问题讨论】:

  • 错误是什么?
  • .NET Core 默认使用 PascalCasing。您的 Angular 模型使用 PascalCasing。看看是否有帮助...请同时捕捉实际调用(调试工具中的网络选项卡)以查看请求是否看起来像它应该的那样。您可以先使用Postman 让调用生效,以便稍后在代码中修复它。

标签: javascript c# json angular .net-core


【解决方案1】:

尝试像这样在正文中发送数据。

post(data) {
           const body = {
                  "column_name1":"data1",
                 "column_name2":"data2",

       };
       const headers = new Headers(
            {
                'accept': 'application/json',
                'content-type': 'application/json'
            });
        const options = new RequestOptions({ headers: headers });
    return this.http.post(this.url, body, options).map((response: Response) => response.json());

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 2018-09-24
    • 2021-04-19
    • 2018-01-24
    • 2019-08-14
    • 2020-02-08
    • 2018-04-20
    • 2018-07-12
    • 2017-08-05
    相关资源
    最近更新 更多