2013-07-17 101 views
4

我試圖使用 '請求' 一個POST的Web API操作返回HttpResponseException的Web API '請求' 爲空

throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "File not in a correct size")); 

在這樣做時,我得到Value cannot be null. Parameter name: request

實質上 - 請求爲空。

我錯過了什麼?

謝謝

+0

確認嘗試使用'拋出新HttpResponseException(HttpStatusCode.NotFound)' – Rwiti

+0

Rwiti嗨,你建議併爲下面的工作還有: '拋出新HttpResponseException(新HttpResponseMessage(HttpStatusCode。InternalServerError) { 內容=新的StringContent( 「無效的大小」), 的StatusCode = HttpStatusCode.Forbidden });' 但是在客戶端(JS)我無法得到 '內容' 性質的保持。任何理念? – Leo

回答

2

使用此:

HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.InternalServerError); 
message.Content = new ObjectContent(typeof(MessageResponse), "Invalid Size", GlobalConfiguration.Configuration.Formatters.JsonFormatter); 
throw new HttpResponseException(message); 

注意:您可以更改「大小無效」,你可能要返回給用戶的任何對象。 例如: -

public ErrorMessage 
{ 
    public string Error; 
    public int ErrorCode; 
} 

ErrorMessage msg = new ErrorMessage(); 
msg.Error = "Invalid Size"; 
msg.ErrorCode = 500; 

HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.InternalServerError); 
message.Content = new ObjectContent(typeof(MessageResponse), msg, GlobalConfiguration.Configuration.Formatters.JsonFormatter); 
throw new HttpResponseException(message); 
+2

謝謝你,這是正確的,但工作,但我仍然想知道爲什麼'請求'在這種情況下爲空。 – Leo

+0

@Leo是否找到答案,爲什麼Request在Web API控制器中爲空? – Toolkit

0

nizari的答案是正確的,但是我最終使用下列內容:

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) 
        { 
         Content = new StringContent("Invalid image dimensions. Image file must be " + image.Width + "x" + image.Height + "px"), 
         StatusCode = HttpStatusCode.Forbidden 
        }); 

,並使用在客戶端訪問內容jqXHR.responseText

謝謝大家!

5

我發現我的Request對象在我的ApiController中爲null,因爲我在另一個嵌套了一個ApiController調用。第二個嵌套的ApiController因此從未初始化。您不能手動初始化它,但是您可以利用Request對象上的setter從包裝器傳遞到嵌套的ApiController。下面是一個模型,在我的真實代碼中它修復了我的Request.CreateErrorResponse(...)錯誤。

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")); 
    } 
} 
+0

此代碼可能只適用於Web Api 1,我相信它不能在Asp.Net Web Api 2中工作 –

0

擴展在nizari的答案,這是我以包括的ErrorMessage對象列表所做的:

IEnumerable errorList = new List<ErrorMessage>(); 

// ... 

var error = new HttpError("There were errors.") 
{ 
    { "Errors", errorList } 
}; 

var message = new HttpResponseMessage(HttpStatusCode.BadRequest) 
{ 
    Content = new ObjectContent<HttpError>(error, GlobalConfiguration.Configuration.Formatters.JsonFormatter) 
}; 

throw new HttpResponseException(message); 
0

你必須創建System.Net.Http.HttpRequestMessage的新實例。下面將工作

 
var request = new HttpRequestMessage(); 
var response = request.CreateErrorResponse(HttpStatusCode.NotFound, "File not in a correct size"); 

throw new HttpResponseException(response); 
-1
HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.InternalServerError); 
message.Content = new ObjectContent(typeof(MessageResponse), 
            "Invalid Size", 
            GlobalConfiguration.Configuration.Formatters.JsonFormatter); 
throw new HttpResponseException(message); 
2

像@ DavB.cs誰嵌套像ApiControllers人們另一種解決方案:

public class ParentController : ApiController 
{ 
    public IHttpActionResult Foo() 
    { 
     ChildRepository.Foo(); 
     return Ok(...); 
    } 
} 

public class ChildRepository : ApiController 
{ 
    public HttpResponseMessage Foo() 
    { 
     // Do something 
     return Request.CreateResponse(...); 
    } 
} 

是簡單地只是請求通過從ParentController這樣:

public class ParentController : ApiController 
    { 
     public IHttpActionResult Foo() 
     { 
      ChildRepository.Foo(Request); 
      return Ok(...); 
     } 
    } 

    public class ChildRepository 
    { 
     public HttpResponseMessage Foo(HttpRequestMessage request) 
     { 
      // Do something 
      return request.CreateResponse(...); 
     } 
    } 

請求來自ApiController。這會讓你通過'請求爲空'的問題。

希望這可以幫助別人。

+1

在所有建議的解決方案中(我也使用過),這是我最喜歡的,謝謝Aaron。 –