c# - 如何添加返回视图?
问题描述
我为每种方法都有一个视图,我在标题中设置了返回的参数,但是如何制作 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);
条线应该指向什么视图?
解决方案
ViewResult 需要更多数据
filterContext.Result = new ViewResult {
ViewName = "YourViewName",
ViewData = // Create your view data here, might be your result
}
也尝试设置异常处理属性。
filterContext.ExceptionHandled = true;
推荐阅读
- java - java.io.FileNotFoundException - zip4j
- acumatica - 新的 Acumatica 系统电子邮件帐户返回“不接受用户名或密码”错误
- java - 正则表达式连接多个匹配项
- r - 有没有办法检查 R 在 for 循环中“卡住”的位置?(右)
- c - Issue with feeding arrays of structs as arguments into pthread_create
- jquery - my multiple versions of jQuery doesn't work
- typo3 - 有没有办法在 TYPO3 9 中通过 extbase 创建域对象翻译?
- c# - 如何从 MS Access 文件中读取数据并使用 T-SQL 或 SSIS 将该数据从每个工作表插入到相应的 SQL Server 数据库表中?
- apache-kafka - 状态存储可能已迁移到另一个实例
- reactjs - 如何将 HTML 输入值流与 UP 或 DOWN 键流以及输入类型流结合起来?