【发布时间】:2018-07-12 13:41:05
【问题描述】:
我正在学习 MVC 和 WEB API 我在 MVC 中有 Controller,它调用 Web Api 以进行进一步的操作。我已经成功地将数据从 API 检索到控制器,但我无法将数据从控制器发布到 API。
在 DAL 部分,我应该将我的值与参数放在哪里。我的数据库是 Oracle
我如何在 API 中获取数据,因为我仍在学习是否需要对此代码进行任何改进,我们将非常感谢您的建议。
我的 MVC 控制器
[HttpPost]
public ActionResult Create(Models.DeviceType device)
{
HttpResponseMessage response;
try
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
response = httpClient.PostAsync(ApiUrl + "DeviceTypeApi/AddDeviceType", device, new JsonMediaTypeFormatter()).Result;
response.EnsureSuccessStatusCode();
return View("GetAllDeviceTypes");
}
}
catch (Exception ex)
{
return View();
}
}
API 控制器
[HttpPost, ActionName("AddDeviceType")]
public HttpResponseMessage AddDeviceType()
{
objDeviceBL = new DeviceBL();
HttpResponseMessage response;
try
{
var deviceResponse = objDeviceBL.AddDeviceType(); //this will further move it to business logic
if (deviceResponse != null)
{
response = Request.CreateResponse<List<Models.DeviceType>>(HttpStatusCode.OK, deviceResponse);
}
else
{
response = new HttpResponseMessage(HttpStatusCode.NotFound);
}
}
catch (Exception ex)
{
response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
return response;
}
BL
internal new List<Models.DeviceType> AddDeviceType()
{
return base.AddDeviceType();
}
核心
protected List<DeviceType> AddDeviceType()
{
List<DeviceType> objDeviceTypes = null;
try
{
objDeviceTypes = new DeviceDAL().AddDeviceType();
}
catch (Exception ex)
{
throw ex;
}
return objDeviceTypes;
}
DAL
public List<DeviceType> AddDeviceType()
{
List<DeviceType> objDeviceTypes = new List<DeviceType>();
using (cmd = new OracleCommand("SP_DMS_DEVICE_TYPE_INSERT", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_typename", OracleType.VarChar).Direction = ParameterDirection.Input;
cmd.Parameters.Add("p_createdby", OracleType.Int32).Direction = ParameterDirection.Input;
cmd.Parameters.Add("p_createdon", OracleType.DateTime).Direction = ParameterDirection.Input;
cmd.Parameters.Add("p_updatedby", OracleType.Int32).Direction = ParameterDirection.Input;
cmd.Parameters.Add("p_updatedon", OracleType.DateTime).Direction = ParameterDirection.Input;
con.Open();
adap = new OracleDataAdapter();
adap.InsertCommand = cmd;
}
catch (Exception)
{
con.Close();
}
return objDeviceTypes;
}
}
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4 asp.net-web-api