网络编程ASP.NET的几个技巧

本文介绍了ASP.NET开发中的一些实用技巧,包括通过代码生成图片、使用System.Web.HttpContext.Current实现页面通用功能、在自定义Web控件中加载内嵌资源脚本文件以及在web.config中设置默认页面基类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.显示通过代码生成的图片

  把生成图片的代码放在一个aspx页面中,在PageLoad事件中把图片写入输出流:

  private void Page_Load(object sender, System.EventArgs e) {

  string code = Request.Params["code"];

  Bitmap image = DrawImage(code);

  Response.ContentType = "image/gif";

  image.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Gif);

  Response.End();

  }

  在需要引用图片的地方,设定图片URL为生成图片的aspx页面:

  ImageCode.ImageUrl = "CodeImage.aspx?code="+code;

  2.使用System.Web.HttpContext.Current来实现一些页面中常用的方法,比如:

  public class WebApp{

  public static void ShowMessage(string message){

  HttpContext.Current.Response.Write ("<script language=javascript>alert('"+message+"')</script>");

  }

  public static string CurrentUser{

  get{

  return HttpContext.Current.Session["UserID"]+"";

  }

  }

  }

  3.在自定义的Web控件中,把Javascript脚本文件编译为内嵌的资源,然后从资源中读取脚本并注册。

  public class Res {

  public static StreamReader GetStream(Type type,string name){

  //Assembly assembly = Assembly.GetAssembly(type);

  Assembly assembly = type.Assembly;

  Stream stream = assembly.GetManifestResourceStream(type,name);

  return new StreamReader(stream);

  }

  }

  public class ScriptControl : Control {

  /// <summary>

  /// Register Client Script Block

  /// </summary>

  /// <param name="control">custom web control</param>

  /// <param name="scriptfile">resource script file name</param>

  public void RegisterScript(string scriptfile){

  if (!this.Page.IsClientScriptBlockRegistered(scriptfile)) {

  StreamReader reader = Res.GetStream(this.GetType(),scriptfile);

  using(reader){

  string script

  = "<script language=/"javascript/" type=/"text/javascript/">/r/n<!——/r/n"

  + reader.ReadToEnd()

  + "/r/n//——>/r/n</script>";

  this.Page.RegisterClientScriptBlock(scriptfile, script);

  }

  }

  }

  }

  [DefaultProperty("Text"),

  ToolboxData("<{0}:ShowDialogListBox runat=server></{0}:ShowDialogListBox>")]

  public class ShowDialogListBox : ScriptControl {

  ……

  protected override void OnInit(EventArgs e) {

  this.RegisterScript("EnDeListBox.js");

  }

  ……

  }

  4.在web.config文件中定义默认的页面继承类型。

  <pages pageBaseType="Msdn.Page" />

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值