博客
关于我
MVC ActionResult派生类关系图
阅读量:415 次
发布时间:2019-03-06

本文共 3539 字,大约阅读时间需要 11 分钟。

MVC框架中的ActionResult及其派生类是Controller方法返回结果的核心机制。本文将详细介绍ActionResult及其常见派生类的用法和特点。

1. ContentResult

ContentResult用于返回简单的纯文本内容,支持通过ContentType属性指定文档类型和ContentEncoding属性指定字符编码。开发者可以通过Controller类中的Content方法直接返回ContentResult对象。如果Controller方法返回的不是ActionResult类型,MVC会将其ToString()内容作为纯文本返回。

示例代码

public ContentResult RSSFeed() {    Story[] stories = GetAllStories();    string encoding = Response.ContentEncoding.WebName;    XDocument rss = new XDocument(new XDeclaration("1.0", encoding, "yes"),         new XElement("rss", new XAttribute("version", "2.0"),             new XElement("channel", new XElement("title", "Example RSS 2.0 feed"),                 from story in stories                 select new XElement("item",                     new XElement("title", story.Title),                     new XElement("description", story.Description),                     new XElement("link", story.Url)                ))    );    return Content(rss.ToString(), "application/rss+xml");}

2. EmptyResult

EmptyResult用于返回空结果。如果Controller方法返回null,MVC会将其转换为EmptyResult对象。这种结果类型通常用于表示无数据可供处理的情况。

3. RedirectResult

RedirectResult表示一个页面跳转,类似于ASP.NET的Response.Redirect方法。Controller方法通常使用Redirect方法来实现跳转功能。

示例代码

public override void ExecuteResult(ControllerContext context) {    if (context == null) {        throw new ArgumentNullException("context");    }    if (context.IsChildAction) {        throw new InvalidOperationException(MvcResources.RedirectAction_CannotRedirectInChildAction);    }    string destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);    context.Controller.TempData.Keep();    context.HttpContext.Response.Redirect(destinationUrl, false /* endResponse */);}

4. RedirectToRouteResult

RedirectToRouteResult用于根据指定的路由信息生成Url地址并执行跳转。它支持通过RouteValueDictionary指定路由参数,适用于需要动态Url生成的情况。

5. ViewResult

ViewResult用于表示一个视图结果,它会根据视图模板生成响应内容。Controller方法通常使用View方法来返回ViewResult对象。

6. PartialViewResult

PartialViewResult类似于ViewResult,但它支持部分视图的加载。与全屏视图不同,部分视图通常用于用户控件(UserControl)的渲染。

7. HttpUnauthorizedResult

HttpUnauthorizedResult表示未经授权的访问错误。MVC会向客户端返回401状态码,并根据配置将Url重定向到登录页面。

8. JavaScriptResult

JavaScriptResult用于返回JavaScript代码。它将Response.ContentType设置为application/x-javascript,适用于需要客户端执行JavaScript代码的情况。

9. JsonResult

JsonResult用于返回JSON格式的数据。MVC会将指定对象序列化为JSON,并将Response.ContentType设置为application/json。需要注意的是,默认情况下MVC不允许GET请求返回JSON结果,需要在生成JsonResult对象时将JsonRequestBehavior属性设置为JsonRequestBehavior.AllowGet。

示例代码

class CityData {    public string city;    public int temperature;}public JsonResult WeatherData() {    var citiesArray = new[] {        new CityData { city = "London", temperature = 68 },        new CityData { city = "Hong Kong", temperature = 84 }    };    return Json(citiesArray);}

10. FileResult及派生类

FileResult是一个抽象类,其子类包括FilePathResult、FileContentResult和FileStreamResult。这些类用于返回文件内容,具体的传输方式在各自子类中有所不同。

示例代码

public FilePathResult DownloadReport() {    string filename = @"c:\files\somefile.pdf";    return File(filename, "application/pdf", "AnnualReport.pdf");}
public FileContentResult GetImage(int productId) {    var product = productsRepository.Products.First(x => x.ProductID == productId);    return File(product.ImageData, product.ImageMimeType);}
public FileStreamResult ProxyExampleDotCom() {    WebClient wc = new WebClient();    Stream stream = wc.OpenRead(http://www.studyofnet.com/);    return File(stream, "text/html");}

结论

ActionResult在MVC框架中扮演着重要角色,它及其派生类为Controller方法提供了丰富的返回结果类型。通过选择合适的ActionResult类型,开发者可以实现各种复杂的Controller逻辑,从简单的内容返回到复杂的文件传输,再到动态的页面跳转和JSON数据序列化。了解这些结果类型的特点和用法,是掌握MVC框架的关键。

转载地址:http://uvlkz.baihongyu.com/

你可能感兴趣的文章
Nim游戏
查看>>
NIO ByteBuffer实现原理
查看>>
Nio ByteBuffer组件读写指针切换原理与常用方法
查看>>
NIO Selector实现原理
查看>>
nio 中channel和buffer的基本使用
查看>>
NIO基于UDP协议的网络编程
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
Nitrux 3.8 发布!性能全面提升,带来非凡体验
查看>>
NI笔试——大数加法
查看>>
NLog 自定义字段 写入 oracle
查看>>
NLog类库使用探索——详解配置
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NLP 项目:维基百科文章爬虫和分类【01】 - 语料库阅读器
查看>>
NLP_什么是统计语言模型_条件概率的链式法则_n元统计语言模型_马尔科夫链_数据稀疏(出现了词库中没有的词)_统计语言模型的平滑策略---人工智能工作笔记0035
查看>>
NLP学习笔记:使用 Python 进行NLTK
查看>>
NLP的神经网络训练的新模式
查看>>
NLP采用Bert进行简单文本情感分类
查看>>
NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
Nmap扫描教程之Nmap基础知识
查看>>