本文整理汇总了C#中System.Web.HttpResponse.Close方法的典型用法代码示例。如果您正苦于以下问题:C# HttpResponse.Close方法的具体用法?C# HttpResponse.Close怎么用?C# HttpResponse.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Web.HttpResponse
的用法示例。
在下文中一共展示了HttpResponse.Close方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DataTableToExcel
/// <summary>
/// Datatable数据填充如excel
/// </summary>
/// <param name="filename">excel文件名</param>
/// <param name="dt"> 数据源</param>
/// <param name="Response"> response响应</param>
/// <param name="headerStr"> 表头标题</param>
public static void DataTableToExcel(string filename, DataTable dt, string sheetname, HttpResponse Response, string headerStr)
{
MemoryStream ms = StreamData(dt, sheetname, headerStr) as MemoryStream; //as MemoryStream as用作转换,此处可以省略
try
{
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = Encoding.UTF8;
Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls"));
Response.AddHeader("content-length", ms.Length.ToString());
Byte[] data = ms.ToArray(); //文件写入采用二进制流的方式。所以此处要转换为字节数组
Response.BinaryWrite(data);
}
catch
{
Response.Clear();
Response.ClearHeaders();
Response.Write("<script language=javascript>alert( '导出Excel错误'); </script>");
}
Response.Flush();
Response.Close();
Response.End();
ms = null;
}
示例2: ExportGridViewToExcel
public void ExportGridViewToExcel(GridView grid, string fileName, HttpResponse Hresponse)
{
Hresponse.Clear();
Hresponse.Buffer = true;
Hresponse.AddHeader("content-disposition", "attachment;fileName=" + fileName + ".xls");
Hresponse.Charset = "";
Hresponse.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
grid.RenderControl(hw);
Hresponse.Output.Write(sw.ToString());
Hresponse.Flush();
Hresponse.Close();
//Hresponse.End();
Hresponse.OutputStream.Close();
}
示例3: Methods_Deny_Unrestricted
public void Methods_Deny_Unrestricted ()
{
HttpResponse response = new HttpResponse (writer);
response.AddCacheItemDependencies (new ArrayList ());
response.AddCacheItemDependency (String.Empty);
response.AddFileDependencies (new ArrayList ());
response.AddFileDependency (fname);
response.AddCacheDependency (new CacheDependency[0]);
response.AddCacheItemDependencies (new string [0]);
response.AddFileDependencies (new string [0]);
try {
response.AppendCookie (new HttpCookie ("mono"));
}
catch (NullReferenceException) {
// ms
}
try {
Assert.IsNull (response.ApplyAppPathModifier (null), "ApplyAppPathModifier");
}
catch (NullReferenceException) {
// ms
}
try {
response.Clear ();
}
catch (NullReferenceException) {
// ms
}
try {
response.ClearContent ();
}
catch (NullReferenceException) {
// ms
}
try {
response.ClearHeaders ();
}
catch (NullReferenceException) {
// ms
}
try {
response.Redirect ("http://www.mono-project.com");
}
catch (NullReferenceException) {
// ms
}
try {
response.Redirect ("http://www.mono-project.com", false);
}
catch (NullReferenceException) {
// ms
}
try {
response.SetCookie (new HttpCookie ("mono"));
}
catch (NullReferenceException) {
// ms
}
response.Write (String.Empty);
response.Write (Char.MinValue);
response.Write (new char[0], 0, 0);
response.Write (this);
response.WriteSubstitution (new HttpResponseSubstitutionCallback (Callback));
response.Flush ();
response.Close ();
try {
response.End ();
}
catch (NullReferenceException) {
// ms
}
}
示例4: TransmitFile
/// <summary>
/// 将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件。
/// </summary>
/// <param name="filePath"></param>
/// <param name="response"></param>
public virtual bool TransmitFile(string fileName, string filePath, HttpResponse Response)
{
#region
var flag = false;
using (ImpersonateUser iu = new ImpersonateUser())
{
ImpersonateUser.ValidUser(iu, _FileServer.Indentity);
//if (File.Exists(filePath))
//{
// response.TransmitFile(filePath);
// flag = true;
//}
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
if (fileInfo.Exists == true)
{
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
byte[] buffer = new byte[ChunkSize];
Response.Clear();
System.IO.FileStream fileStream = System.IO.File.OpenRead(filePath);
long dataTotalLength = fileStream.Length;
int readDataLength = 0;
while (dataTotalLength > 0 && Response.IsClientConnected)
{
readDataLength = fileStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));
Response.OutputStream.Write(buffer, 0, readDataLength);
Response.Flush();
dataTotalLength = dataTotalLength - readDataLength;
}
Response.Close();
flag = true;
}
}
return flag;
#endregion
}
示例5: Get
public override void Get(HttpResponse response, string relativePath, UrlEncodedMessage message) {
if (string.IsNullOrEmpty(message["action"])) {
response.StatusCode = 200;
response.Write("No Action Specified.");
}
switch (message["action"]) {
case "add":
if (!string.IsNullOrEmpty(message["location"])) {
try {
var uri = new Uri(message["location"]);
if (Peek(uri)) {
var filename = "UploadedFile.bin".GenerateTemporaryFilename();
var rf = new RemoteFile(uri, filename);
rf.Get();
if (File.Exists(filename)) {
HandleFile(filename).ContinueWith(antecedent => {
if (antecedent.IsFaulted) {
var e = antecedent.Exception.InnerException;
HandleException(e);
response.StatusCode = 500;
response.Close();
} else {
response.StatusCode = antecedent.Result;
response.Close();
}
}).Wait();
return;
}
}
} catch {
}
}
break;
case "validate":
Validate().ContinueWith(antecedent => {
if (antecedent.IsFaulted) {
var e = antecedent.Exception.InnerException;
HandleException(e);
response.StatusCode = 500;
response.Close();
} else {
response.StatusCode = antecedent.Result;
response.Close();
}
}).Wait();
return;
break;
case "makewebpi":
var txt = RegenerateWebPI();
response.ContentType = "application/xml";
response.StatusCode = 200;
response.Write(txt);
// response.Close();
return;
case "test":
var txt2 = "Hello World";
// response.ContentType = "application/text";
response.StatusCode = 200;
response.Write(txt2);
// response.Close();
return;
}
response.StatusCode = 500;
response.Close();
}
示例6: Put
public override void Put(HttpResponse response, string relativePath, byte[] data) {
if (data.Length < 1) {
response.StatusCode = 500;
response.Close();
return;
}
var filename = "UploadedFile.bin".GenerateTemporaryFilename();
File.WriteAllBytes(filename, data);
HandleFile(filename).ContinueWith(antecedent => {
if (antecedent.IsFaulted) {
var e = antecedent.Exception.InnerException;
HandleException(e);
response.StatusCode = 500;
response.Close();
} else {
response.StatusCode = antecedent.Result;
response.Close();
}
}).Wait();
filename.TryHardToDelete();
}
示例7: Post
public override void Post(HttpResponse response, string relativePath, UrlEncodedMessage message) {
var payload = message["payload"];
if( payload == null ) {
response.StatusCode = 500;
response.Close();
return;
}
Logger.Message("payload = {0}",payload);
try {
dynamic json = JObject.Parse(payload);
Logger.Message("MSG Process begin {0}", json.commits.Count);
var count = json.commits.Count;
var doSiteRebuild = false;
for (int i = 0; i < count; i++) {
string username = json.commits[i].author.email.Value;
var atSym = username.IndexOf('@');
if( atSym > -1 ) {
username = username.Substring(0, atSym);
}
var commitMessage = json.commits[i].message.Value;
var repository = json.repository.name.Value;
var url = (string)json.commits[i].url.Value;
if (repository == "coapp.org") {
doSiteRebuild = true;
}
Bitly.Shorten(url).ContinueWith( (bitlyAntecedent) => {
var commitUrl = bitlyAntecedent.Result;
var handle = _aliases.ContainsKey(username) ? _aliases[username] : username;
var sz = repository.Length + handle.Length + commitUrl.Length + commitMessage.Length + 10;
var n = 140 - sz;
if (n < 0) {
commitMessage = commitMessage.Substring(0, (commitMessage.Length + n) - 1) + "\u2026";
}
_tweeter.Tweet("{0} => {1} via {2} {3}", repository, commitMessage, handle, commitUrl);
Logger.Message("{0} => {1} via {2} {3}", repository, commitMessage, handle, commitUrl);
});
}
// just rebuild the site once for a given batch of rebuild commit messages.
if( doSiteRebuild) {
Task.Factory.StartNew(() => {
try {
Logger.Message("Rebuilding website.");
Bus.SendRegenerateSiteMessage();
} catch( Exception e ) {
HandleException(e);
}
});
}
} catch(Exception e) {
Logger.Error("Error handling uploaded package: {0} -- {1}\r\n{2}", e.GetType(), e.Message, e.StackTrace);
HandleException(e);
response.StatusCode = 500;
response.Close();
}
}
示例8: HandleUpdate
public static void HandleUpdate(HttpRequest Request, HttpResponse Response)
{
ClientControlsReader r = new ClientControlsReader(Request.InputStream);
byte[] buffer;
FileStream inFile = null;
try
{
Response.ClearContent();
ClientControlsWriter w = new ClientControlsWriter(Response.OutputStream);
int updateManagerVersion = int.Parse(Request["updateManagerVersion"]);
int controlReleaseVersion = int.Parse(Request["controlReleaseVersion"]);
int processorArchitecture = int.Parse(Request["processorArchitecture"]);
bool win95 = Request["platform"] == "95";
int winMajor = int.Parse(Request["winmajor"]);
int winMinor = int.Parse(Request["winminor"]);
string winCsd = Request["winCsd"];
string gdiplusVerString = Request["gdiplusver"].Trim();
bool hasGdiplus = gdiplusVerString != "0.0";
bool adminInstall = bool.Parse(Request["admin"]);
bool hasMfc71 = bool.Parse(Request["mfc71"]);
string[] files;
if(!hasGdiplus)
files = new string[] { "gdiplus", "minakortcontrols" };
else
files = new string[] { "minakortcontrols" };
//Write version
w.Write(updateManagerVersion);
//Write response code
w.Write(1);
//Write response message
string message = "";
w.WriteString(message);
//Write file count
w.Write(files.Length);
//Write total file size
int totalSize=0;
foreach(string file in files)
{
string filePath = HttpContext.Current.Server.MapPath(Configuration.RootPath+ "public/" + file + ".dll");
totalSize += (int)new FileInfo(filePath).Length;
}
w.Write(totalSize);
//Write files
foreach(string file in files)
{
string clientFileName;
if(file == "minakortcontrols")
{
w.Write((byte)(1));
clientFileName = "minakortcontrols.2.dll";
}
else
{
w.Write((byte)(0));
clientFileName = "gdiplus.dll";
}
//Write client file name
w.WriteString(clientFileName);
string filePath = HttpContext.Current.Server.MapPath(Configuration.RootPath+ "public/" + file + ".dll");
inFile = new FileStream(filePath, FileMode.Open, FileAccess.Read);
w.Write((int)inFile.Length);
buffer = new byte[inFile.Length];
inFile.Read(buffer,0,buffer.Length);
w.Write(buffer);
inFile.Close();
inFile = null;
}
}
finally
{
if(inFile != null)
inFile.Close();
Response.Flush();
Response.Close();
Response.End();
}
}
示例9: HandleCategoryLookup
static void HandleCategoryLookup(HttpRequest Request, HttpResponse Response, Guid userId)
{
try
{
Response.ClearContent();
ClientControlsWriter w = new ClientControlsWriter(Response.OutputStream);
//Version
w.Write((int)1);
//ResultCode
if(userId == Guid.Empty)
{
w.Write((int)-1);
return;
}
string categoryName = Request["categoryName"];
if(categoryName == null)
categoryName = string.Empty;
categoryName = categoryName.Trim();
if(!Validation.ValidateCategoryName(categoryName))
{
w.Write((int)-2);
return;
}
w.Write((int)0);
// } result code.
Database.MemberDetails details = Database.GetMemberDetails(null, userId);
Guid existingId = Database.GetSubCategory(userId, details.HomeCategoryId, categoryName);
Database.Category cat = null;
if(existingId != Guid.Empty)
cat = Database.GetCategoryInfo(userId, existingId);
w.Write(existingId != Guid.Empty);
w.Write(existingId.ToByteArray());
//canAddPermission
w.Write(cat != null && cat.CurrentPermission >= Permission.Add);
//securityPermission
w.Write(cat != null && cat.CurrentPermission >= Permission.Owner); //TODO: shold be securitypermission.
w.WriteString(cat != null?cat.Name:categoryName);
//can't send email
w.Write((byte)0x00);
//can't share to friends
w.Write((byte)0x00);
//Write the permission entries on the category.
if(existingId == Guid.Empty)
w.Write(0);
else
{
Guid groupId = Database.GetMemberGroup(userId, "$"+existingId);
Database.GroupMember[] members = Database.EnumGroupMembers(userId, groupId);
w.Write((uint)(members.Length-1)); //minus self
foreach(Database.GroupMember member in members)
{
if(member.MemberId == userId)
continue;
Database.MemberDetails md = Database.GetMemberDetails(null, member.MemberId);
w.Write((byte)0);
w.Write(md.Id.ToByteArray());
w.WriteString(md.admin_username);
w.WriteString(md.admin_email);
w.WriteString(md.Name);
w.Write((uint)0);
w.Write((uint)0);
w.Write((uint)0);
w.Write((uint)0);
}
}
}
finally
{
Response.Flush();
Response.Close();
Response.End();
}
}
示例10: HandleUserLookup
public static void HandleUserLookup(HttpRequest Request, HttpResponse Response, Guid userId)
{
try
{
ClientControlsReader r = new ClientControlsReader(Request.InputStream);
Response.ClearContent();
ClientControlsWriter w = new ClientControlsWriter(Response.OutputStream);
w.Write(1);
string query = Request["userquery"];
//Write result code
if(query == null || query.Length == 0)
{
w.Write(-1);
return;
}
else
w.Write(0);
query = "%"+query+"%";
ArrayList data = new ArrayList();
using(Db db = new Db())
{
db.CommandText = @"
SELECT id, fullNameClean as fullName, username, email
FROM tMember
WHERE fullName LIKE @q OR email LIKE @q OR username LIKE @q
ORDER BY fullNameClean ASC
";
db.AddParameter("@q", query);
while(db.Read())
{
UserInfo user = new UserInfo();
user.username = (string)db["username"];
user.id = (Guid)db["id"];
user.email = db["email"] as string;
user.name = (string)db["fullName"];
data.Add(user);
}
}
w.Write((int)data.Count);
foreach(object o in data)
{
if(o is UserInfo)
{
w.Write((byte)0);
UserInfo user = (UserInfo)o;
w.Write(user.id.ToByteArray());
w.WriteString(user.username);
w.WriteString(user.email);
w.WriteString(user.name);
}
}
int a = 3;
}
finally
{
Response.Flush();
Response.Close();
Response.End();
}
}
示例11: HandleUploadControl
public static void HandleUploadControl(HttpRequest Request, HttpResponse Response)
{
Guid userId = Guid.Empty;
try
{
HttpCookie cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if(cookie != null && cookie.Value != null && cookie.Value.Length > 0)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
if(ticket != null && ticket.Name != null && ticket.Name.Length > 0)
userId = new Guid(ticket.Name);
}
if(userId == Guid.Empty)
userId = Principal.MemberIdOrZero;
}
catch(Exception exc)
{
Log.LogDebug(exc);
}
string v = Request["v"];
int version = v!=null&&v.Length>0?int.Parse(v):0;
string action = Request["action"];
try
{
Response.ClearContent();
if(action == "upload")
HandleUploadControlUpload(Request, Response, userId);
else if(action == "login")
HandleUploadControlLogin(Request, Response);
else if(action == "updatedetails")
HandleDetailsUpdate(Request, Response, userId);
else if(action == "userlookup")
HandleUserLookup(Request, Response, userId);
else if(action == "categorylookup")
HandleCategoryLookup(Request, Response, userId);
else if(action == "createcategory")
HandleCreateCategory(Request, Response, userId);
else
{
BinaryWriter w = new BinaryWriter(Response.OutputStream);
w.Write(new byte[8]);
}
}
finally
{
Response.Flush();
Response.Close();
Response.End();
}
}
示例12: FinalErrorWrite
static void FinalErrorWrite (HttpResponse response, string error)
{
try {
response.Write (error);
response.Flush (true);
} catch {
response.Close ();
}
}
示例13: EndRequestOnRequestLengthExceeded
/// <summary>
/// Ends the request if the maximum request length is exceeded.
/// </summary>
/// <param name="response">The HTTP response.</param>
void EndRequestOnRequestLengthExceeded(HttpResponse response)
{
response.StatusCode = 400; // Generic 400 error just like ASP.Net
response.StatusDescription = "Maximum request size exceeded";
response.Flush();
response.Close();
}