在ASP.net MVC中通过web服务向数据库发送数据

本文关键字:服务 数据库 数据 web net ASP MVC | 更新日期: 2023-09-27 18:11:20

在一个着色文件下,我有几个项目。UI (ASP。. Net mvc)项目,我的rest服务项目,DTO项目,业务逻辑项目和数据访问。现在,我的服务项目的控制器需要与我的UI(ASP)对话。Net MVC)项目的控制器,获取表单中输入的数据并将其发送到数据库。我很不确定我应该在UI项目的控制器类中提出的逻辑。UI项目也单独拥有实体类。需要帮助! !

This is the POST method in my services controller
// POST api/Maintenance
    [HttpPost]
    public IHttpActionResult Post([FromBody]Maintenance maintenance)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        maintenanceLogic.Insert(maintenance);
        return CreatedAtRoute("DefaultApi", new { id = maintenance.WorkID }, maintenance);
    }

这是将访问上述方法uri的方法。这个方法在我的UI项目的控制器类中。我想出了一个逻辑。但我认为这是不对的。

       [HttpPost, Route("/maintenance/CreateMaintenanceOrder")]
    public PartialViewResult CreateMaintenanceOrder([FromBody] Maintenance Model)
    {
        Model.CheckItems = maintenanceViewModel.CheckItems;
        Model.CrewMembers = maintenanceViewModel.CrewMembers;
        Model.WorkID = ++SessionUtility.CurrentMaintenanceID;
        try
        {
            var uri = "api/Maintenance/Post  ";
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri("http://localhost:8961");
                Task<String> request = httpClient.GetStringAsync(uri);
                Model = JsonConvert.DeserializeObject<List<Maintenance>>(request.Result);
            }
            maintenanceViewModel.MaintenanceOrders.Add(Model);
        }
        catch (AggregateException e)
        {
        }
        maintenanceViewModel.MaintenanceOrders.Add(Model);
        return PartialView("_Search", maintenanceViewModel);
    }

在ASP.net MVC中通过web服务向数据库发送数据

您正在尝试使用GetAsync调用Post方法,并且似乎您没有通过Rest服务方法所需的维护对象作为输入。请在下面尝试-

string maintenanceData = JsonConvert.SerializeObject(Model); //considering you have to pass Model as input to Rest method
HttpResponseMessage response = httpClient.PostAsync(new Uri("http://localhost:8961" + "api/Maintenance/Post/"), new StringContent(maintenanceData));