2017-07-16 66 views
1

我试图从我的webAPI控制器的POST方法之一发送响应。在数据库中,这些值得到保存,但在try和catch中发送响应时,抛出以下异常。ASP.NET WebAPI发送响应错误

异常消息:“值不能为空参数名称:请求。”

控制器方法代码:

[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); 
     } 
    } 

enter image description here

请让我知道我需要做的来解决这个问题。谢谢。

调用从如下一MVC的控制器方法的API控制器的方法,

EmployeeController empCtrl = new EmployeeController(); 
empCtrl.AddEmployee(emp); 
+0

你可以在你调用这个方法的地方添加你的代码吗? – zzT

+0

@zzT更新了我的问题,并详细介绍了我所说的API控制器方法。请检查。 – Manju

+1

@Manju你为什么手动创建控制器?该API创建它作为请求流的一部分。通过手动创建它,你不会填充其他所需的属性,比如'Request',这就是为什么你的'Request'是'null'的原因。 – Nkosi

回答

2

您手动创建控制器。该框架通常将其作为请求流的一部分。通过手动创建它,你不填充其他所需的属性,如Request这就是为什么你的Requestnull

将您希望从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 
} 

的网络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控制器可以使用相同的服务也是如此。

0

实际扩展方法CreateResponse抱怨得到一个空引用。 Nkosi的答案在技术上是正确的,但为了防止大量重构,只需更改您的控制器注册,以便您在此处使用的控制器直接响应请求(就像您打算从此处给出的代码一样)