![](/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.