一、类型介绍:
1. ContentResult 使ASP.NET MVC 采用我们提供的内容来响应请求;
如果Action 方法执行后的返回值是一个ActionResult , ActionInvoker会直接利用它来进行请求响应,否则它会将对象转换成字符串并以此创建一个ContentResult 对象。
2. 抽象类Controller 定义了如下三个受保护的Content 方法重载,可以调用它们根据指定的内容、编码和媒体类型创建相应的ContentResult,具体定义如下:
public abstract class Controller : ControllerBase,
{
protected ContentResult Content(string content);
protected ContentResult Content(string content , string contentType);
protected virtual ContentResult Content(string content , string contentType, Encoding contentEncoding);
}
ContentResult 包含三个属性:
A. Content 属性:以字符串的形式指定响应的内容;
B. ContentEncoding属性:指定内容字符编码方式;
C. ContentType属性:媒体类型(MIME枚举类型);
public class ContentResult : ActionResult
{
public ContentResult();
public string Content { get; set; }
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public override void ExecuteResult(ControllerContext context);
}
3.ExecuteResult 方法:
重写ActionResult父类的的ExecuteResult 方法中, ContentResult 利用作为参数的ControllerContext 对象得到当前的HttpResponse 对象,并借助它将提供的内容按照希望的编码方式和媒体类型对请求予以响应,具体实现如下:
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = this.ContentType;
}
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Content != null)
{
response.Write(this.Content);
}
}