是否有可能拦截动作成为ContentResult?

时间:2016-06-30 15:46:03

标签: c# asp.net asp.net-mvc-4

我正在尝试编写一个包含数据的过滤器,以跟随JSON API spec,到目前为止,我已经将它用于直接返回ActionResult的所有情况,例如ComplexTypeJSON。我试图让它在像ComplexType这样的情况下工作,我不必经常运行Json函数。

[JSONAPIFilter]
public IEnumerable<string> ComplexType()
{
    return new List<string>() { "hello", "world" };
}

[JSONAPIFilter]
public JsonResult ComplexTypeJSON()
{
    return Json(new List<string>() { "hello", "world" });
}

但是,当我导航到public override void OnActionExecuted(ActionExecutedContext filterContext)时,当ComplexType运行时,filterContext.Result是一个内容结果,这只是filterContext.Result.Content只是一个字符串:< / p>

"System.Collections.Generic.List`1[System.String]"

我是否有办法设置一些内容以使ComplexType成为JsonResult而不是ContentResult

对于上下文,这里是确切的文件:

TestController.cs

namespace MyProject.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;

    using MyProject.Filters;

    public class TestController : Controller
    {
        [JSONAPIFilter]
        public IEnumerable<string> ComplexType()
        {
            return new List<string>() { "hello", "world" };
        }

        [JSONAPIFilter]
        public JsonResult ComplexTypeJSON()
        {
            return Json(new List<string>() { "hello", "world" });
        }

        // GET: Test
        [JSONAPIFilter]
        public ActionResult Index()
        {
            return Json(new { foo = "bar", bizz = "buzz" });
        }

        [JSONAPIFilter]
        public string SimpleType()
        {
            return "foo";
        }

        [JSONAPIFilter]
        public ActionResult Throw()
        {
            throw new InvalidOperationException("Some issue");
        }
    }
}

JSONApiFilter.cs

namespace MyProject.Filters
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using MyProject.Exceptions;
    using MyProject.Models.JSONAPI;

    public class JSONAPIFilterAttribute : ActionFilterAttribute, IExceptionFilter
    {
        private static readonly ISet<Type> IgnoredTypes = new HashSet<Type>()
                                                              {
                                                                  typeof(FileResult),
                                                                  typeof(JavaScriptResult),
                                                                  typeof(HttpStatusCodeResult),
                                                                  typeof(EmptyResult),
                                                                  typeof(RedirectResult),
                                                                  typeof(ViewResultBase),
                                                                  typeof(RedirectToRouteResult)
                                                              };

        private static readonly Type JsonErrorType = typeof(ErrorModel);

        private static readonly Type JsonModelType = typeof(ResultModel);

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (IgnoredTypes.Any(x => x.IsInstanceOfType(filterContext.Result)))
            {
                base.OnActionExecuted(filterContext);
                return;
            }

            var resultModel = ComposeResultModel(filterContext.Result);
            var newJsonResult = new JsonResult()
                                    {
                                        JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                                        Data = resultModel
                                    };

            filterContext.Result = newJsonResult;
            base.OnActionExecuted(filterContext);
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var modelState = filterContext.Controller.ViewData.ModelState;

            if (modelState == null || modelState.IsValid)
            {
                base.OnActionExecuting(filterContext);
            }
            else
            {
                throw new ModelStateException("Errors in ModelState");
            }
        }

        public virtual void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (filterContext.Exception == null) return;

            // Todo: if modelstate error, do not provide that message
            // set status code to 404

            var errors = new List<string>();

            if (!(filterContext.Exception is ModelStateException))
            {
                errors.Add(filterContext.Exception.Message);
            }

            var modelState = filterContext.Controller.ViewData.ModelState;
            var modelStateErrors = modelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList();
            if (modelStateErrors.Any()) errors.AddRange(modelStateErrors);

            var errorCode = (int)System.Net.HttpStatusCode.InternalServerError;
            var errorModel = new ErrorModel()
                                 {
                                     status = errorCode.ToString(),
                                     detail = filterContext.Exception.StackTrace,
                                     errors = errors,
                                     id = Guid.NewGuid(),
                                     title = filterContext.Exception.GetType().ToString()
                                 };
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            filterContext.HttpContext.Response.StatusCode = errorCode;

            var newResult = new JsonResult() { Data = errorModel, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

            filterContext.Result = newResult;
        }

        private ResultModel ComposeResultModel(ActionResult actionResult)
        {
            var newModelData = new ResultModel() { };

            var asContentResult = actionResult as ContentResult;
            if (asContentResult != null)
            {
                newModelData.data = asContentResult.Content;
                return newModelData;
            }

            var asJsonResult = actionResult as JsonResult;
            if (asJsonResult == null) return newModelData;

            var dataType = asJsonResult.Data.GetType();
            if (dataType != JsonModelType)
            {
                newModelData.data = asJsonResult.Data;
            }
            else
            {
                newModelData = asJsonResult.Data as ResultModel;
            }

            return newModelData;
        }
    }
}

3 个答案:

答案 0 :(得分:3)

有两种选择:

1.使用 ApiController 代替控制器

apicontroller将返回json结果,默认序列化器为 Newtonsoft.json (here),因此您可以使用如下所示:

//the response type
public class SimpleRes
{
    [JsonProperty(PropertyName = "result")]
    public string Result;      
}

//the controller
 public class TestController : ApiController
 {  
    [HttpGet] 
    [HttpPost]
    [JSONAPIFilter]
    public SimpleRes TestAction()
    {
        return new SimpleRes(){Result = "hello world!"};
    }
 }

2.如果您坚持使用控制器,请使用您自己的 ActionResult 包裹您的回复:

//json container
public class AjaxMessageContainer<T>
{        
    [JsonProperty(PropertyName = "result")]
    public T Result { set; get; }
}

//your own actionresult
public class AjaxResult<T> : ActionResult
{        
    private readonly T _result;                      

    public AjaxResult(T result)
    {          
        _result = result;           
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.ContentType = "application/json";
        var result = JsonConvert.SerializeObject(new AjaxMessageContainer<T>
        {               
            Result = _result,               
        });
        var bytes =
            new UTF8Encoding().GetBytes(result);
        context.HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length);           
    }
}

//your controller
[JSONAPIFilter]
public AjaxResult<List<String>> TestSimple()
{
    return AjaxResult<List<String>>(new List<string>() { "hello", "world" });
}

如果您想从过滤器获取日志或其他内容的响应字符串:

var result  = filterContext.Response.Content.ReadAsStringAsync();

答案 1 :(得分:3)

我认为这就是你要找的东西:

public class JSONAPIFilterAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext context)
    {
        context.Result = new JsonResult
        {
            Data = ((ViewResult)context.Result).ViewData.Model
        };
    }
}
  

来自@roosteronacid:return jsonresult in actionfilter

答案 2 :(得分:0)

我刚刚遇到同样的问题,发现了一种略有不同的方法。 基本想法来自NOtherDev。 我会介绍IActionInvoker

public class ControllerActionInvokerWithDefaultJsonResult : ControllerActionInvoker
{
    public const string JsonContentType = "application/json";

    protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
    {
        if (controllerContext.HttpContext.Request.Path.StartsWith("/api/"))
        {
            return (actionReturnValue as ActionResult) 
                ?? new JsonResult
                {
                    Data = actionReturnValue,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
        }
        return base.CreateActionResult(controllerContext, actionDescriptor, actionReturnValue);
    }
}

在这种情况下,以“/ api /”开头的每个请求都会将结果转换为json,但仅当actionReturnValue不是从ActionResult继承的类型时才会生效。

{p> IActionInvokerDependencyResolver解决,因此您需要在您最喜欢的ioc容器中定义注册,并将其设置为DependencyResolver

myFavoriteContainer.Register<IActionInvoker, ControllerActionInvokerWithDefaultJsonResult>(Lifestyle.Transient);

对于JsonResult,您可以使用内置或this

如果您使用异步操作方法,则应该从AsyncControllerActionInvoker而不是ControllerActionInvoker继承,我假设您还需要为IAsyncActionInvoker添加另一个注册。我不确定调用者本身的异步部分是否有变化。