简体   繁体   English

Dotnet 核心 Web API 正在从角度形式获取 Null 数据

[英]Dotnet core web API is getting Null data from angular form

I have created dotnet core Web Api of CRUD operations, I tested it with postman and works fine, Then I implemented an angular form interface to get the data and passes it to the web Api.我已经创建了 CRUD 操作的 dotnet core Web Api,我用 postman 测试了它并且工作正常,然后我实现了一个 angular form interface 来获取数据并将其传递给 web Api。 But I noticed that I am getting a record with null values, after that the web api won't work even with postman.但是我注意到我得到了一个空值的记录,之后即使邮递员也无法使用 web api。 works only when I delete the null record created by angular.仅当我删除由 angular 创建的空记录时才有效。

This is the method class这是方法类

export class AddCustomerComponent implements OnInit {

  addCustomerForm: FormGroup;

  constructor(private service: CustomerService, private fb: FormBuilder, private router: Router) {}

  ngOnInit(): void {

    this.addCustomerForm = this.fb.group({

  VersionId : [null, Validators.required],

  Name : [null, Validators.required],

  Url : [null, Validators.required],

  Dns : [null, Validators.required],

    })
  }
  onSubmit(){
    this.service.addCustomer(this.addCustomerForm.value).subscribe(data => {
      this.router.navigate(["/customers"]);
    })
  }

}

.Net Core api Controller .Net Core api 控制器

[HttpPost("AddCustomer")]
        public IActionResult AddCustomer([FromBody]Customer customer)
        {
            if (!ModelState.IsValid) return BadRequest(ModelState);
            using (var context = new HrmapsMasterContext())
            {
                context.Customer.Add(customer);
                context.SaveChanges();
                return Ok();

            }
        }

Form code:表格代码:

<div class="add-customer">
    <form [formGroup]="addCustomerForm" (ngSubmit)="onSubmit()">

        <div class="form-group">
            <label for="versionid" class="required">Id</label>
            <input type="number" class="form-control" id="versionId" formComtrolName="versionId" placeholder="Version Id ">
        </div>
        <div class="form-group">
            <label for="name" class="required">HR Portail</label>
            <input type="text" class="form-control" id="name" formComtrolName="name" placeholder="Url">
        </div>
        <div class="form-group">
            <label for="url" class="required">Job Portail</label>
            <input type="text" class="form-control" id="url" formComtrolName="url" placeholder="Url">
        </div>
        <div class="form-group">
            <label for="dns" class="required">DNS</label>
            <input type="text" class="form-control" id="dns" formComtrolName="dns" placeholder="dns">
        </div>



        <button class="btn btn-success" type="submit">Add</button>
        <button class="btn btn-default" [routerLink]="['/customers']">Cancel</button>

    </form>
    </div>

Here's my angular service code:这是我的角度服务代码:

    export class CustomerService {

    _baseURL: string = "api/customers"

    constructor(private http: HttpClient) { }
    getAllCustomers(){
      return this.http.get<customer[]>(this._baseURL+"/getcustomers");

    }
    addCustomer(Customer: customer){


      const customerForAPI = {

        VersionId: Customer.VersionId,
        Name: Customer.Name,
        Url: Customer.Url,
        Dns: Customer.Dns

      };


      const body = JSON.stringify(customerForAPI);
      console.log(body);

      return this.http.post<customer>(this._baseURL +'/addcustomer/', body, { headers });

    }
  }

and here's my web api customer model, please notice that I have used Entityframeworkcore the reverse engineer an existing database这是我的 web api 客户模型,请注意我使用了 Entityframeworkcore 对现有数据库进行逆向工程

    public partial class Customer
    {
        public Customer()
        {
            Pack = new HashSet<Pack>();
        }

        public int Id { get; set; }
        public int? VersionId { get; set; }
        public string Website { get; set; }
        public string Twitter { get; set; }
        public string Map { get; set; }
        public string Fax { get; set; }
        public string Name { get; set; }
        public string Ceoname { get; set; }
        public string Activity { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string City { get; set; }
        public string Url { get; set; }
        public string Locality { get; set; }
        public string Street { get; set; }
        public string Town { get; set; }
        public string ZipCode { get; set; }
        public string ConnectionString { get; set; }
        public string Dns { get; set; }
        public bool? IsActive { get; set; }
        public bool? IsDeleted { get; set; }
        public DateTime? LicenseStartDate { get; set; }
        public DateTime? LicenseEndDate { get; set; }
        public Guid? GuidCustomer { get; set; }

        public virtual AppVersion Version { get; set; }
        public virtual ICollection<Pack> Pack { get; set; }
    }
}

here an xml post request works fine with postman这里的 xml post 请求与邮递员一起工作正常

{ "id": 2078, "versionId": null, "website": null, "twitter": null, "map": null, "fax": null, "name": null, "ceoname": null, "activity": null, "email": null, "phone": null, "city": null, "url": null, "locality": null, "street": null, "town": null, "zipCode": null, "connectionString": null, "dns": null, "isActive": false, "isDeleted": null, "licenseStartDate": null, "licenseEndDate": null, "guidCustomer": null, "version": null, "pack": [] } { "id": 2078, "versionId": null, "website": null, "twitter": null, "map": null, "fax": null, "name": null, "ceoname": null, "活动": null, "email": null, "phone": null, "city": null, "url": null, "locality": null, "street": null, "town": null, "zipCode" : null, "connectionString": null, "dns": null, "isActive": false, "isDeleted": null, "licenseStartDate": null, "licenseEndDate": null, "guidCustomer": null, "version": null , “盒”: [] }

You could try:你可以试试:

const headers: HttpHeaders = new HttpHeaders()
  .set('Content-Type', 'application/json');

export class CustomerService {
.
.
.
addCustomer(customer: Customer) {
    const customerForAPI = {
      // Here your customerForAPI has to correspond to your C# customer class
      VersionId: customer.versionId,
      Name: customer.name,
      Url: customer.url,
      Dns: customer.dns
    };
    const body = JSON.stringify(customerForAPI);
    console.log(body);
    return this.http.post<Customer>(this._baseURL +'/addcustomer/', body, { headers });
  }

我错过了拼写 formControlName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CORS 问题 Angular MSAL Azure AD Do.net Core Web API - CORS Issue with Angular MSAL Azure AD Dotnet Core Web API 如何使用mailkit将联系表单数据发送到API(Angular 7 + .Net core web api) - How to send contact form-data to API using mailkit (Angular 7 + .Net core web api) dotnet 核心中的自定义 Json 格式化程序 Web API - Custom Json Formatter in dotnet core Web API .net core web app JQuery AJAX前端没有从后端.net core api获取数据 - .net core web app JQuery AJAX Front end not getting data from Backend .net core api dotnet核心从网址末尾获取ID - dotnet core getting id from end of url GraphQL Web Api 使用 .NET 核心并具有 null 数据值? - GraphQL Web Api using .NET Core and having null data values? Mock IOptions 从 do.net 核心中的 secret.json 文件获取配置数据的最佳选择是什么 - What is the best option to Mock IOptions for getting configured data from secret.json file in dotnet core dotnet core 3.1 web api 开发 sql 连接在服务器上失败 - dotnet core 3.1 web api development sql connection fail on server 将在 dotnet 4.5 框架中开发的 web API 2.0 转换为 dotnet Core 2.1.4 - Convert web API 2.0 developed in dotnet 4.5 framework to dotnet Core 2.1.4 如何从外部网站获取数据到.NET Core中的Web API? - How to get data from external website into a web API in .NET core?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM