ContentResult(内容)类型

  一、类型介绍:

     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);

                      }
            }


     

  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值