首页 > 解决方案 > 如何添加返回视图?

问题描述

我为每种方法都有一个视图,我在标题中设置了返回的参数,但是如何制作 VIEW?

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Formatters.Xml.Extensions;
using System;

namespace ProjectAboutProjects
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    public sealed class FormatReponseFilterAttribute : Attribute, IActionFilter
    {
        private enum FormatResponseType { Json, Xml, View, Unknown }
        private FormatResponseType _requestedType { get; set; }
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var _result = (ObjectResult) filterContext.Result;
            switch (_requestedType)
            {
                //https://localhost:44342/api/Post/Search?id=qwe
                case FormatResponseType.Json:
                var data = new { Data = _result.Value };
                filterContext.Result = new JsonResult(data);
                break;
                case FormatResponseType.Xml:
                filterContext.Result = new XmlResult(_result.Value);
                break;
                case FormatResponseType.View:
                //filterContext.Result = new ViewResult(_result.Value);// Don't worl(
                break;

                case FormatResponseType.Unknown:
                default:
                throw new InvalidOperationException("Uknown Content Type ain Accept Header");
            }
        }
    }
}

问题:return filterContext.Result = new ViewResult (_result.Value);条线应该指向什么视图?

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

解决方案


ViewResult 需要更多数据

   filterContext.Result = new ViewResult { 
       ViewName = "YourViewName", 
       ViewData = // Create your view data here, might be your result
   }

也尝试设置异常处理属性

   filterContext.ExceptionHandled = true;

推荐阅读