![](/img/trans.png)
[英]An error when sending PATCH with Postman to Asp.net Core webapi
[英]ASP.NET WebAPI error on sending response
我正在尝试从webAPI控制器的POST方法之一发送响应。 在DB中,值已保存,但是在try和catch中发送响应时,将引发以下异常。
异常消息:“值不能为null。参数名称:request。”
控制器方法代码:
[HttpPost]
public HttpResponseMessage AddEmployee(Employee emp)
{
try
{
using (EmployeeEntities dbEntity = new EmployeeEntities())
{
dbEntity.Configuration.LazyLoadingEnabled = false;
dbEntity.Employees.Add(emp);
dbEntity.SaveChanges();
return Request.CreateResponse(HttpStatusCode.Created, emp); // EXCEPTION IS THROWN HERE
}
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
请让我知道解决该问题需要做什么。 谢谢。
从MVC控制器方法调用API控制器方法,如下所示:
EmployeeController empCtrl = new EmployeeController();
empCtrl.AddEmployee(emp);
您正在手动创建控制器。 框架通常将其创建为请求流的一部分。 通过手动创建它,您不会填充其他必需的属性,例如Request
,这就是您的Request
为null
。
从Web API中提取要执行的操作到服务中,然后将其注入到MVC和Web API控制器中。 这样,MVC控制器无需创建API控制器。
一些简单的例子
public EmployeeService : IEmployeeService {
public Employee AddEmployee(Employee emp) {
using (EmployeeEntities dbEntity = new EmployeeEntities()) {
dbEntity.Configuration.LazyLoadingEnabled = false;
dbEntity.Employees.Add(emp);
dbEntity.SaveChanges();
return emp;
}
}
//...other service members
}
Web API将使用该服务
public class EmployeeController : ApiController {
private readonly IEmployeeService employeeService;
public EmployeeController(IEmployeeService service) {
this.employeeService = service;
}
[HttpPost]
public HttpResponseMessage AddEmployee(Employee emp) {
try {
employeeService.AddEmployee(emp);
return Request.CreateResponse(HttpStatusCode.Created, emp);
} catch(Exception ex) {
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
//...other actions.
}
MVC控制器也可以使用相同的服务。
实际的扩展方法CreateResponse抱怨获取空引用。 Nkosi的回答在技术上是正确的,但是为了防止大量重构,只需更改您的控制器注册,以便您在此处使用的控制器可以直接响应请求(就像您打算从此处提供的代码中获得意图一样)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.