[常见问题]cookie使用1.Page与HttpContext的Request、Response

自编程序如下

using

System;
using System.Web;
using System.Web.UI;
namespace hnwl.config
{
///
<summary>
///
Cookdef 的摘要说明。
///
cookies相关的定义,以及涉及到cook的一些检验,如用户登录标示
///
</summary>
public class Cookdef :Page
{
  private HttpCookie cook;
  public Cookdef()
  {
  
//
   // TODO: 在此处添加构造函数逻辑
  //
   }
   public void New(string name)
   {
    cook=new HttpCookie(name);
   }
   public HttpCookie Req(string name)
   {
     cook=Request.Cookies[name];
     return cook;
    }
    public void Append()
    {
      Response.Cookies.Add(cook);
//运行后提示此行出错
    }

编译过程未提示错误,但是运行后出现 System.Web.HttpException: 响应在此上下文中不可用;将Request.Cookies[name]和Response.Cookies.Add(cook)改成HttpContext.Current.Request.Cookies[name]和HttpContext.Current.Response.Cookies.Add(cook)即恢复正常。

解释:Page中的Response,Request只能在页面文件中使用(尽管上文定义的是Cookdef :Page,但只是作为普通类使用),而HttpContext可以在任何情况下使用,可获取当前的上下文数据。

using Avary.Service; using Avary.Tools; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Avary.FPC.Materials { /// <summary> /// By Lot領料數量 /// </summary> public partial class MaterialsNumByLot : System.Web.UI.Page { FpcMaterialNumService materialService = new FpcMaterialNumService(); CommonTool comm = new CommonTool(); string bu = string.Empty; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GvDataBind(); } } private void GvDataBind() { HttpCookie cookie = Request.Cookies["TK"]; string userid = cookie["Userid"]; //判斷userid所屬BU權限 DataTable dtBu = materialService.GetRoleInfoByUserId(userid); if (dtBu.Rows.Count > 0) { bu = dtBu.Rows[0]["BU"].ToString(); } else { bu = " "; } string partnum = TB_PARTNUM.Text.Trim(); int currentPage = Convert.ToInt16(PLB_CURRENT_PAGE.Text); int pageSize = Convert.ToInt16(PDL_SHOW_SIZE.SelectedValue); RenderDataFooter(partnum,bu, currentPage, pageSize, "count"); DataTable dt = materialService.GetMaterialsBylot(partnum, bu, currentPage, pageSize, "section"); GV.DataSource = dt; GV.DataBind(); } private void RenderDataFooter(string partnum, string bu, int currentPage, int pageSize, string pageType) { DataTable dt = materialService.GetMaterialsBylot(partnum, bu, currentPage, pageSize, pageType); PLB_TOTAL_PAGE.Text = dt.Rows[0]["TOTAL_PAGE"].ToString(); PLB_TOTAL.Text = dt.Rows[0]["TOTAL"].ToString(); // previous button control if (PLB_CURRENT_PAGE.Text.Equals("1")) { PLI_PRE.Attributes.Add("class", "paginate_button previous disabled"); PBT_PRE.Enabled = false; } else { PLI_PRE.Attributes.Add("class", "paginate_button previous"); PBT_PRE.Enabled = true; } // next button control if (PLB_CURRENT_PAGE.Text.Equals(PLB_TOTAL_PAGE.Text)) { PLI_NEXT.Attributes.Add("class", "paginate_button previous disabled"); PBT_NEXT.Enabled = false; } else { PLI_NEXT.Attributes.Add("class", "paginate_button previous"); PBT_NEXT.Enabled = true; } } protected void GV_RowCommand(object sender, GridViewCommandEventArgs e) { GridViewRow gvr = ((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));//此得出的值是表示那行被选中的索引值 string cn = e.CommandName; int i = gvr.RowIndex; Label lb_partnum = gvr.Cells[0].FindControl("DAQDB_PARTNUM") as Label; Label lb_pnlEdition = gvr.Cells[0].FindControl("DAQDB_PNL") as Label; Label lb_strip = gvr.Cells[0].FindControl("DAQDB_STRIP") as Label; Label lb_material = gvr.Cells[0].FindControl("DAQDB_MATERIAL_LOT") as Label; Label lb_control = gvr.Cells[0].FindControl("DAQDB_CONTROL") as Label; string partnum = lb_partnum.Text; string pnl_edition = lb_pnlEdition.Text; string strip_edition = lb_strip.Text; string material_lot = lb_material.Text; string sys_control = lb_control.Text; HttpCookie cookie = Request.Cookies["TK"]; string userid = cookie["Userid"]; //判斷userid所屬BU權限 DataTable dtBu = materialService.GetRoleInfoByUserId(userid); if (dtBu.Rows.Count > 0) { bu = dtBu.Rows[0]["BU"].ToString(); } bool checkRole = materialService.CheckRole(cookie["Userid"]); if (checkRole == false) { Response.Write("<script>alert('你沒有權限, 請找相關人員開通!')</script>"); return; } switch (cn) { default: break; case "EDT": Response.Redirect($"MaterialsBylotAdd.aspx?PARTNUM={partnum}&PNL_EDITION={pnl_edition}&STRIP_EDITION={strip_edition}&MATERIAL_LOT={material_lot}&SYS_CONTROL={sys_control}&BU={bu}"); break; case "DELE": bool result = materialService.DeleteLotRow(partnum, bu); if (result) { HttpContext.Current.Response.Write("<script>alert(JSON.parse(localStorage.langhelpmsg)['1']);location.assign('MaterialsNumByLot.aspx');</script>"); //HttpCookie cookie = Request.Cookies["TK"]; //Username if (null != cookie && null != cookie["Userid"] && null != cookie["Username"]) { string usernumber = cookie["Userid"].ToString().Trim(); string username = cookie["Username"].ToString().Trim(); new Logger().WriteLog("[料號:" + partnum + "][PNL排版:" + pnl_edition +"][分條排版:"+ strip_edition + "][每LOT取料:"+ material_lot+ "][系統卡控"+ sys_control +"][刪除時間:" + DateTime.Now.ToLongTimeString() + "][操作者姓名:" + Server.UrlDecode(username) + "][工號:" + usernumber + "]"); } GvDataBind(); } else { comm.alertMsg(2); } break; } } // 點擊查詢按鈕 protected void BT_SEARCH_ServerClick(object sender, EventArgs e) { PLB_CURRENT_PAGE.Text = "1";//當在第N頁點擊查詢的時候 GvDataBind(); } //EXCEL匯出 protected void BT_EXPORT_ServerClick(object sender, EventArgs e) { string partnum = TB_PARTNUM.Text.Trim(); HttpCookie cookie = Request.Cookies["TK"]; string userid = cookie["Userid"]; //判斷userid所屬BU DataTable dtBu = materialService.GetRoleInfoByUserId(userid); if (dtBu.Rows.Count > 0) { bu = dtBu.Rows[0]["BU"].ToString(); } int currentPage = Convert.ToInt16(PLB_CURRENT_PAGE.Text); int pageSize = Convert.ToInt16(PDL_SHOW_SIZE.SelectedValue); DataTable dt = materialService.GetMaterialsBylot(partnum, bu, currentPage, pageSize, "data"); var name = DateTime.Now.ToString("yyyyMMddHHmmssfff"); Random r = new Random(); var rf = string.Empty; for (int j = 0; j < 10; j++) { rf = r.Next(int.MaxValue).ToString(); } comm.DateTableToExcel(dt, name + "_" + rf, "sheet1"); } //首页 protected void PBT_FIRST_Click(object sender, EventArgs e) { PLB_CURRENT_PAGE.Text = "1"; GvDataBind(); } //上一页 protected void PBT_PRE_Click(object sender, EventArgs e) { if (PBT_PRE.Enabled) { PLB_CURRENT_PAGE.Text = (Convert.ToInt32(PLB_CURRENT_PAGE.Text) - 1).ToString(); GvDataBind(); } } //下一页 protected void PBT_NEXT_Click(object sender, EventArgs e) { if (PBT_NEXT.Enabled) { PLB_CURRENT_PAGE.Text = (Convert.ToInt32(PLB_CURRENT_PAGE.Text) + 1).ToString(); GvDataBind(); } } //尾页 protected void PBT_LAST_Click(object sender, EventArgs e) { PLB_CURRENT_PAGE.Text = PLB_TOTAL_PAGE.Text; GvDataBind(); } //跳轉 protected void PBT_GO_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(PTB_PAGE.Text.Trim())) { comm.alertMsg(2, "請輸入正確的頁數!"); return; } else { PLB_CURRENT_PAGE.Text = PTB_PAGE.Text; GvDataBind(); } } protected void PDL_SHOW_SIZE_SelectedIndexChanged(object sender, EventArgs e) { GvDataBind(); } } }
最新发布
12-30
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值