Web API"请求"为空

Leo*_*Leo 5 c# asp.net-mvc asp.net-web-api

我正在尝试HttpResponseException使用"请求"从POST Web API操作返回:

throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "File not in a correct size"));
Run Code Online (Sandbox Code Playgroud)

这样做,我明白了Value cannot be null. Parameter name: request.

基本上 - 请求为空.

我错过了什么?

谢谢

小智 5

我在我的ApiController中发现我的Request对象为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"));
    }
}
Run Code Online (Sandbox Code Playgroud)


noz*_*ari 2

用这个:

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

注意:您可以使用您可能想要为用户返回的任何对象来更改“无效大小”。例如:

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);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,它是正确的并且确实有效,但是我仍然想知道为什么“Request”在这种情况下为空。 (2认同)