从方法响应API时发生404错误

时间:2019-12-11 10:00:58

标签: reactjs api asp.net-core

在此项目中,Get方法有效,并且标头也应用在API中。当我发布给与者错误404 (加载资源失败:服务器响应状态为400(错误请求))

在Api Modal中,我有以下代码:

    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace Pay_Roll_Managment_System.Models
{
    public class Employee
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //Id auto-generated by the database
        public int EmployeeId { get; set; }
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
        [Required]
        public string Address { get; set; }
        [Required]
        public DateTime Birthdate { get; set; }
        [Required]
        public string ContactInfo { get; set; }
        [Required]
        public bool Gender { get; set; } // 1 == male , 0 == female
        [Required]
        public string RegistrationNo { get; set; }

        public string ImgUrl { get; set; }
        [Required]
        public DateTime CreatedOn { get; set; }

        [ForeignKey("PoistionId")]
        public Position Position { get; set; }
        public int PoistionId { get; set; }

    }
}

在控制器中,我有以下代码用于post方法

     [HttpPost]
        [ProducesResponseType(201, Type = typeof(Employee))]
        [ProducesResponseType(500)]

        public IActionResult CreateEmpoyee([FromBody]Employee EmployeeToCreate)
        {
            if (EmployeeToCreate ==null)
            {
                return BadRequest(ModelState);
            }

            //Checking the method of Employee forign key. 2 if conditions have to be satisified

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            //creating employee
            if (!_EmployeeRepository.CreateEmployee(EmployeeToCreate))
            {
                return StatusCode(500, ModelState);
            }
            return CreatedAtRoute("GetEmployee", new { EmployeeId = EmployeeToCreate.EmployeeId });

        }

在React Post组件中,我有以下代码

    import React from 'react';
import {Component} from 'react';
import {Modal,Button,Row,Col, Form} from 'react-bootstrap';
import Snackbar from '@material-ui/core/Snackbar';
import IconButton from '@material-ui/core/IconButton';


export class EmployeeRegPop extends Component {
    constructor(props) {
        super(props);
        this.state = {Snackbaropen:false,Snackbarmsg:''}
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    SnackbarClose = (event)=>{
    this.setState({Snackbaropen:false,
    })
  }

    handleSubmit(event){
      event.preventDefault();
        fetch('http://localhost:xxxxxx/api/employees',{
          method:'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
          },
          body:JSON.stringify({
            id:null,
            FirstName:event.target.FirstName.value,
            LastName:event.target.LastName.value,
            Address:event.target.Address.value,
            Birthdate:event.target.Birthdate.value,
            ContactInfo:event.target.ContactInfo.value,
            Gender:event.target.Gender.value,
            RegistrationNo:event.target.RegistrationNo.value,
            CreatedOn:event.target.CreatedOn.value,
            PoistionId:event.target.PoistionId.value,
          })
        })
        .then(res=>res.json())
        .then((result)=>
        {
             alert(result)
            this.setState({SnackbarOpen:true, Snackbarmsg:"Added Successfully"})
        },
        (error)=>{
          this.setState({SnackbarOpen:true, Snackbarmsg:"failed"})
        })
    }
    render() {
        return (
          <div className ="container">

          <Snackbar
            anchorOrigin ={{vertical:'bottom',horizontal:'center'}}
            open = {this.state.Snackbaropen}
            autoHideDuration = {3000}
            onClose = {this.SnackbarClose}
            message = {<span id ="message-id">{this.state.Snackbarmsg}</span>}
            action ={[
              <IconButton
                key = "close"
                arial-label="Close"
                color ="inherit"
                onClick={this.SnackbarClose}>
                x
              </IconButton>
            ]}
          />

            <Modal
              {...this.props}
              size="lg"
              aria-labelledby="contained-modal-title-vcenter"
              centered
            >
              <Modal.Header closeButton>
                <Modal.Title id="contained-modal-title-vcenter">
                  Employee Registration
                </Modal.Title>
              </Modal.Header>
              <Modal.Body>

            <Row>
                <Col sm= {6}>
                    <Form onSubmit ={this.handleSubmit}>

                        <Form.Group controlId ="FirstName">
                        <Form.Label> First Name</Form.Label>
                        <Form .Control
                        type ="text"
                        name = "FirstName"
                        required
                        placeholder ="First Name"
                        />
                        </Form.Group>

                        <Form.Group controlId ="LastName">
                        <Form.Label>Last Name</Form.Label>
                        <Form .Control
                        type ="text"
                        name = "LastName"
                        required
                        placeholder ="Last Name"
                        />
                        </Form.Group>

                        <Form.Group controlId ="Address">
                        <Form.Label>Address</Form.Label>
                        <Form .Control
                        type ="text"
                        required
                        name = "Address"
                        placeholder ="Address"
                        />
                        </Form.Group>

                        <Form.Group controlId ="Birthdate">
                        <Form.Label>Birth Date</Form.Label>
                        <Form .Control
                        type ="Date"
                        name = "Birthdate"
                        placeholder ="Birth date"
                        />
                        </Form.Group>

                        <Form.Group controlId ="Gender">
                        <Form.Label>Gender</Form.Label>
                        <Form .Control
                        type ="text"
                        name = "Gender"
                        placeholder ="Gender"
                        />
                        </Form.Group>

                        <Form.Group controlId ="ContactInfo">
                        <Form.Label>contact Info</Form.Label>
                        <Form .Control
                        type ="number"
                        name = "ContactInfo"
                        placeholder ="contact Info"
                        />
                        </Form.Group>

                        <Form.Group controlId ="RegistrationNo">
                        <Form.Label>Registration No</Form.Label>
                        <Form .Control
                        type ="text"
                        name = "RegistrationNo"
                        placeholder ="Registration No"
                        />

                        <Form.Group controlId ="CreatedOn">
                        <Form.Label>Created On</Form.Label>
                        <Form .Control
                        type ="Date"
                        name = "CreatedOn"
                        placeholder ="Created On"
                        />
                        </Form.Group>

                        <Form.Group controlId ="PoistionId">
                        <Form.Label>Position Id</Form.Label>
                        <Form .Control
                        type ="int"
                        name = "PoistionId"
                        placeholder ="Position Id"
                        />
                        </Form.Group>
                        </Form.Group>
                        <Form.Group>
                        <Button variant ="primary" type = "submit">
                        Add Employee</Button>
                        </Form.Group>
                    </Form>
                </Col>
            </Row>
      </Modal.Body>
      <Modal.Footer>
        <Button variant ="danger" onClick={this.props.onHide}>Close</Button>
      </Modal.Footer>
    </Modal>
    </div>
        )
    }
}

export default EmployeeRegPop

请帮助查找错误,我现在正在处理此错误2天。我还有其他要求,请告知。

0 个答案:

没有答案