如何在ActionFilter中获取Viewbag.Title数据?

时间:2016-12-19 12:12:08

标签: asp.net asp.net-mvc

我在MVC中创建了ActionFilter,将视图内容转换为JSON,我想获取OnResultExecuted方法中视图中包含的ViewBag.Title参数?。我可以得到我想要的参数吗?

public class ViewToJSON : ActionFilterAttribute
{
    private HtmlTextWriter tw;
    private StringWriter sw;
    private StringBuilder sb;
    private HttpWriter output;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {        
        sb = new StringBuilder();
        sw = new StringWriter(sb);
        tw = new HtmlTextWriter(sw);
        output = (HttpWriter)filterContext.RequestContext.HttpContext.Response.Output;
        filterContext.RequestContext.HttpContext.Response.Output = tw;
        filterContext.RequestContext.HttpContext.Response.ContentType = "application/json";          
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);           
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = "~/Views/Layouts/_Empty.cshtml";
        }           
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        var settings = new HtmlMinificationSettings
        {
            WhitespaceMinificationMode = WhitespaceMinificationMode.Aggressive,
            RemoveRedundantAttributes = false,
            RemoveHttpProtocolFromAttributes = true,
            RemoveHttpsProtocolFromAttributes = true,
            AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes

        };
        var htmlMinifier = new HtmlMinifier(settings);

        MarkupMinificationResult result = htmlMinifier.Minify(sb.ToString(), generateStatistics: true);                

        string json_title = "JSON - ";
        string json_content = "{";
        json_content = json_content + "\"title\":";
        json_content = json_content + "\""+ json_title +"\",";
        json_content = json_content + "\"head\":";
        json_content = json_content + "\"\",";
        json_content = json_content + "\"body\":{";
        json_content = json_content + "\"json_content\":";
        json_content = json_content + JsonConvert.SerializeObject(result.MinifiedContent.ToString());
        json_content = json_content+"},";
        json_content = json_content + "\"foot\":";
        json_content = json_content + "\"\"";
        json_content = json_content + "}";
        output.Write(json_content);       

        base.OnResultExecuted(filterContext);           
    }
}

1 个答案:

答案 0 :(得分:-1)

试试这个:

filterContext.Controller.ViewBag.tilte= "Hello";