I found that my Request object was null in my ApiController because I nested one call of ApiController in another. Therefore, the second, nested ApiController was never initialized. You cannot initialize it manually, but you can use the setter of the Request object to pass from the shell to the nested ApiController. The layout below, in my real code, he fixed the Request.CreateErrorResponse (...) error.
public class WrapperController : ApiController { // POST api/wrapper public void Post(ComplexWithChild value) { var other = value.otherdata; var childcontroller = new ChildController(); childcontroller.Post(value.child); // ChildController is not initialized, and has null Request /*inside ChildController...// causes null reference exception due to null Request Request.CreateErrorResponse(HttpStatusCode.BadRequest, "my message"); */ childcontroller.Request = this.Request; childcontroller.Post(value.child); // ChildController uses same Request /*inside ChildController...// this works now Request.CreateErrorResponse(HttpStatusCode.BadRequest, "my message"); */ } } public class ChildController : ApiController { public void Post(Child value) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "my message")); } }
source share