context.Response.End()的用法和本质

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace Web_Cassini
 7 {
 8     /// <summary>
 9     /// response1 的摘要说明
10     /// </summary>
11     public class response1 : IHttpHandler
12     {
13 
14         public void ProcessRequest(HttpContext context)
15         {
16             context.Response.ContentType = "text/plain";
17             string username = context.Request["username"];
18             string password = context.Request["password"];
19             if(string.IsNullOrWhiteSpace(username))
20             {
21                 context.Response.Write("用户名不能为空" + "
");
22                 //return;
23                 try
24                 {
25                     context.Response.End(); //本质就是一个抛异常--> 效率低能不用最好不用
26                     //EndHandler(context);
27                 }
28                 catch(Exception ex)
29                 {
30                     context.Response.Write(ex.ToString());
31                 }
32             }
33             if (string.IsNullOrWhiteSpace(password))
34             {
35                 context.Response.Write("密码不能为空"+"
");
36                 //return;
37                 //context.Response.End(); 
38                 EndHandler(context);
39             }
40             context.Response.Write("插入成功" + "
");
41         }
42 
43         private void EndHandler(HttpContext context)
44         {
45             context.Response.Write("终止HttpHandler" + "
");
46             context.Response.End();  //子方法中终止进程 只有抛异常才能终止当前执行 不能用return End()本质就是抛出线程异常
47         }
48 
49         public bool IsReusable
50         {
51             get
52             {
53                 return false;
54             }
55         }
56     }
57 }
context.Response.End()的用法和本质

context.Response.End()的用法和本质:

用法:可以用来终止进程,即当前HttpHandler的执行,

  也可以在子方法中终止HttpHandler的执行,

  实际在子方法中终止程序,只有一种可能,那就是程序抛异常,所以context.Response.End()得本质就是抛出了线程异常

  由于抛异常的效率较低,所以能不能就不用,在主方法中最好还是使用return;终止程序比较好,

  但是在子方法中只能使用抛异常终止程序,即使用context.Response.End()终止程序。

原文地址:https://www.cnblogs.com/adolphyang/p/4769902.html