網絡編程ASP.NET的幾個技巧

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" />

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章