1.Client呼叫WebApi
2.WebApi Controller繼承主要Class
3.主要Class繼承ApiController
這次Controller的某個Action使用要其他Class的Method,並接收執行結果(HttpResponseMessage)
Controller Code:
public HttpResponseMessage CheckId(string id) { ClassEmployee Employee = new ClassEmployee(); HttpResponseMessage response = Employee.Chk(id); return response; }
Class Code:
public class Employee { public HttpResponseMessage Chk(string id) { //code... if(HasEmployee) { return Request.CreateResponse(HttpStatusCode.OK); } else { return Request.CreateResponse(HttpStatusCode.NotFound); } } }
在繼承的時候都很正常,而C#又不支援多重繼承,用建立物件的方式去呼叫Method,就出現了下面的錯誤:
ExceptionMessage: 值不能為 null。參數名稱: request ExceptionType: System.ArgumentNullException StackTrace:於 System.Net.Http.HttpRequestMessageExtensions.CreateResponse(HttpRequestMessage request, HttpStatusCode statusCode)
原來是因為建立物件的時候,呼叫Controller的Request並不會傳進去,所以Class的Request是null
在建立物件的時候我們要先初始化Class的Request
Controller Code:
public HttpResponseMessage CheckId(string id) { ClassEmployee Employee = new ClassEmployee() { Request = new HttpResponseMessage() } HttpResponseMessage response = Employee.Chk(id); return response; }
以上就可以正常執行
MVC4 TDD-System.ArgumentNullException: 值不能为空。
Unit testing a ASP.NET WebAPI controller
沒有留言 :
張貼留言