如何在HttpActionContext.response中传递类对象?

时间:2017-03-29 09:13:11

标签: api

我创建了一个API控制器并实现了ActionFilterAttribute,并尝试将结果作为类对象。

public class AuthorizationAttribute : ActionFilterAttribute
{
    ErrorInformation objError = new ErrorInformation();

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (string.IsNullOrEmpty(token))
        {
            objError.ErrorMessage = "Missing Request Token";
            objError.StatusCode = Convert.ToInt16(HttpStatusCode.ExpectationFailed);
            objError.ErrorType = "";
            objError.ErrorCode = "E:101";                  

            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
            {
                Content = new StringContent("Missing Request Token"),
            };

           // Here i want to pass my above class object 'objError' in 'actionContext.Response'
           // it is possible to pass 'objError' as a result ?**
            return;
        }
    }       
}

1 个答案:

答案 0 :(得分:2)

经过一番研究后,我已成功解决了以下问题。

public class AuthorizationAttribute : ActionFilterAttribute
{
    ErrorInformation objError = new ErrorInformation();

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (string.IsNullOrEmpty(token))
        {
            objError.ErrorMessage = "Missing Request Token";
            objError.StatusCode = Convert.ToInt16(HttpStatusCode.ExpectationFailed);
            objError.ErrorType = "";
            objError.ErrorCode = "E:101";                  

            //actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
            // {
            //    Content = new StringContent("Missing Request Token"),
            //};

           // For pass class object as a response          
           var request = actionContext.Request;

           actionContext.Response = request.CreateResponse<ErrorInformation>(HttpStatusCode.BadRequest, objError);

           return;
        }
    }       
}