首页 > 解决方案 > 无法评估子级更新方法未被称为 blazor

问题描述

我正在尝试使用以下语句调用 api 以更新来自 webproject 的记录

public async Task UpdateEmployee(Employee employee)
        {
            var employeeJson =
                new StringContent(JsonSerializer.Serialize(employee), Encoding.UTF8, "application/json");
            await _httpClient.PutAsync("api/employee", employeeJson);             
        }

但是当我调试变量 employeeJson 时,显示错误“无法评估孩子”数据被传递给变量 employee,如下所示

{
    "employeeId": 3,
    "firstName": "sfdsfdsfsd",
    "lastName": "fdgf",
    "birthDate": "2020-09-30T19:09:26.075",
    "email": "ppp@gmail.com",
    "street": "sdfdsfdsf",
    "zip": "sdfsdfds",
    "city": "sdfsdf",
    "countryId": 1,
    "country": {
        "countryId": 1,
        "name": "Belgium"
    },
    "phoneNumber": "1211",
    "maritalStatus": 0,
    "gender": 0,
    "comment": "sdfdsfds",
    "joinedDate": "2020-09-30T19:09:26.124",
    "exitDate": "2020-09-30T00:00:00",
    "jobCategoryId": 1,
    "jobCategory": {
        "jobCategoryId": 1,
        "jobCategoryName": "Pie research"
    }
    
}

我的网络 API 启动.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddDbContext<AppDbContext>(options => options.UseInMemoryDatabase(databaseName: "BethanysPieShopHRM"));

            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddScoped<ICountryRepository, CountryRepository>();
            services.AddScoped<IJobCategoryRepository, JobCategoryRepository>();
            services.AddScoped<IEmployeeRepository, EmployeeRepository>();

            services.AddCors(options =>
            {
                options.AddPolicy("Open", builder => builder.AllowAnyOrigin().AllowAnyHeader());
            });
             



            services.AddControllers();
            //.AddJsonOptions(options => options.JsonSerializerOptions.ca);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();
      
        app.UseCors("Open");
       


        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

回购以获取员工记录

public Employee GetEmployeeById(int employeeId)
        {
             
            return _appDbContext.Employees
                .Include(e => e.Country)
                .Include(e=>e.JobCategory)
                .FirstOrDefault(c => c.EmployeeId == employeeId);
            
        }

我尝试通过邮递员进行更新,但错误消息显示为“错误 405”请求是使用该资源不支持的请求方法对资源提出的

我从 API 控制器调用的方法如下所示

[HttpPut]
        public IActionResult UpdateEmployee([FromBody] Employee employee)
        {
            if (employee == null)
                return BadRequest();

            if (employee.FirstName == string.Empty || employee.LastName == string.Empty)
            {
                ModelState.AddModelError("Name/FirstName", "The name or first name shouldn't be empty");
            }

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

            var employeeToUpdate = _employeeRepository.GetEmployeeById(employee.EmployeeId);

            if (employeeToUpdate == null)
                return NotFound();

            _employeeRepository.UpdateEmployee(employee);

            return NoContent(); //success
        }

标签: apiblazor

解决方案


您几乎可以使用依赖注入来获取值。在 .razor 类中,如果您想使用存储库通过 ID 获取员工,请执行以下操作。

[Inject]
public IEmployeeRepository EmployeeRepository {get;set;}

public void MyMethod()

{ var employeeToUpdate = EmployeeRepository.GetEmployeeById(employee.EmployeeId);

}


推荐阅读