ASP.NET的隐藏功能

时间:2020-03-05 18:50:58  来源:igfitidea点击:
This question exists because it has
  historical significance, but it is not
  considered a good, on-topic question
  for this site, so please do not use it
  as evidence that you can ask similar
   questions here.
  
  More info: https://stackoverflow.com/faq

在边缘场景中总会有一些有用的功能,但是由于这个原因,大多数人都不了解它们。我要的是教科书通常不教授的功能。

你知道些什么?

解决方案

回答

这似乎是一个巨大,模糊的问题...
但是我将介绍反射,因为它使我能够执行一些不可思议的强大功能,例如可插拔DAL等。

回答

HttpModules。该架构是疯狂的优雅。也许不是隐藏的功能,但仍然很酷。

回答

HttpContext.Items作为请求级缓存工具

回答

HttpContext.IsCustomErrorEnabled是一个很酷的功能。我发现它不止一次有用。这是一篇简短的文章。

回答

我想到两件事:

1)我们可以通过以下代码打开和关闭跟踪:

#ifdef DEBUG 
   if (Context.Request.QueryString["DoTrace"] == "true")
                {
                    Trace.IsEnabled = true;
                    Trace.Write("Application:TraceStarted");
                }
#endif

2)我们可以仅使用一个共享的"代码隐藏"文件来构建多个.aspx页面。

建立一个class .cs文件:

public class Class1:System.Web.UI.Page
    {
        public TextBox tbLogin;

        protected void Page_Load(object sender, EventArgs e)
        {

          if (tbLogin!=null)
            tbLogin.Text = "Hello World";
        }
    }

然后我们可以拥有任意数量的.aspx页(在删除VS生成的.designer.cs和.cs代码后)之后:

<%@ Page Language="C#"  AutoEventWireup="true"  Inherits="Namespace.Class1" %>
     <form id="form1" runat="server">
     <div>
     <asp:TextBox  ID="tbLogin" runat="server"></asp: TextBox  >
     </div>
     </form>

我们可以在ASPX中拥有不出现在Class1中的控件,反之亦然,但是我们需要记住检查控件是否为空。

回答

我们可以使用:

Request.Params[Control.UniqueId]

要获取控件的值,请先初始化viewstate(此时Control.Text等为空)。

这对于Init中的代码很有用。

回答

  • HttpContext.Current将始终使我们能够访问当前上下文的Request / Response / etc。
  • 我们可以通过调用Response.Redirect(url,false)将用户重定向到另一个页面,然后继续在同一页面上执行代码。
  • 如果只需要一个已编译的Page(或者任何IHttpHandler),则不需要.ASPX文件。只需将路径和HTTP方法设置为指向web.config文件中&lt;httpHandlers>元素中的类即可。
  • 可以通过调用PageParser.GetCompiledPageInstance(virtualPath,aspxFileName,Context)以编程方式从.ASPX文件中检索Page对象。

回答

throw new HttpException(404, "Article not found");

这将被ASP.NET捕获,它将返回customErrors页面。在最近的.NET每日贴士中了解到这一点

回答

默认情况下,自定义控件的标记之间的任何内容都将添加为子控件。可以在AddParsedSubObject()重写中对其进行拦截以进行过滤或者其他解析(例如,对LiteralControls中的文本内容进行解析):

protected override void AddParsedSubObject(object obj)
     { var literal = obj as LiteralControl;
       if (literal != null) Controls.Add(parseControl(literal.Text));
       else base.AddParsedSubObject(obj);
     }

...

<uc:MyControl runat='server'>
     ...this text is parsed as a LiteralControl...
  </uc:MyControl>

回答

如果放置名为app_offline.htm的文件
在Web应用程序目录的根目录中,ASP.NET 2.0+将关闭该应用程序,并停止正常处理该应用程序的任何新传入请求,仅显示所有新请求的app_offline.htm文件的内容。

这是在重新部署(或者回滚)生产服务器更改时显示"站点暂时不可用"通知的最快,最简单的方法。

另外,正如marxidad指出的那样,请确保文件中至少有512字节的内容,以便IE6可以正确呈现它。

回答

ScottGu在http://weblogs.asp.net/scottgu/archive/2006/04/03/441787.aspx有很多技巧

回答

如果我们让ASP.NET生成RSS源,则有时会在页面顶部加一行。这将无法使用常见的RSS验证器进行验证。我们可以通过将页面伪指令" <@Page>"放在页面底部来解决此问题。

回答

当我将xmlDocument()转储到标签中并使用xsl转换显示时,我认为它很整洁。

回答

基于目标浏览器等设置服务器控件属性。

<asp:Label runat="server" ID="labelText" 
    ie:Text="This is IE text" 
    mozilla:Text="This is Firefox text" 
    Text="This is general text" 
/>

那有点让我惊讶。

回答

在ASP.NET v3.5添加路由之前,我们可以简单地通过编写HTTPModule来创建自己的友好URL,并在页面管道中尽早重写请求(如BeginRequest事件)。

类似http:// servername / page / Param1 / SomeParams1 / Param2 / SomeParams2之类的URL会映射到如下所示的另一页(通常使用正则表达式)。

HttpContext.RewritePath("PageHandler.aspx?Param1=SomeParms1&Param2=SomeParams2");

DotNetNuke有一个非常好的HttpModule,用于其友好的URL。对于无法部署.NET v3.5的计算机仍然有用。

回答

包含在ASP.NET 3.5 SP1中:

  • customErrors现在支持值为" ResponseRewrite"的" redirectMode"属性。显示错误页面而不更改URL。
  • 现在,表单标签可以识别动作属性。非常适合在使用URL重写时

回答

在测试期间,我们可以将电子邮件发送到计算机上的文件夹而不是SMTP服务器。将其放在web.config中:

<system.net>
    <mailSettings>
        <smtp deliveryMethod="SpecifiedPickupDirectory">
            <specifiedPickupDirectory pickupDirectoryLocation="c:\Temp\" />
        </smtp>
    </mailSettings>
</system.net>

回答

将位于App_Code文件夹中的类添加到"全局应用程序类"文件。

ASP.NET 2.0 Global.asax代码隐藏文件。

这也可以在Visual Studio 2008中使用。

回答

我们可以通过使用其UniqueID属性找到任何控件:

Label label = (Label)Page.FindControl("UserControl1$Label1");

回答

HttpContext.Current.IsDebuggingEnabled

这对于确定要输出哪些脚本(最小或者完整版本)或者我们可能需要在开发中但不存在的其他功能非常有用。

回答

System.Web.VirtualPathUtility

回答

我们可以在.aspx页面中使用ASP.NET注释来注释掉页面的整个部分,包括服务器控件。被注释掉的内容将永远不会发送给客户端。

<%--
    <div>
        <asp:Button runat="server" id="btnOne"/>
    </div>
--%>

回答

VS阻塞的有效语法:

<input type="checkbox" name="roles" value='<%# Eval("Name") %>' 
  <%# ((bool) Eval("InRole")) ? "checked" : "" %> 
  <%# ViewData.Model.IsInRole("Admin") ? "" : "disabled" %> />

回答

我开发了一个asp.net应用程序,该应用程序由一家领先的安全公司进行了安全审核,并且我了解了防止这一鲜为人知但很重要的安全漏洞的简单技巧。

以下说明来自:
http://www.guidanceshare.com/wiki/ASP.NET_2.0_Security_Guidelines_-_Parameter_Manipulation#Consider_Using_Page.ViewStateUserKey_to_Counter_One-Click_Attacks

考虑使用Page.ViewStateUserKey来抵抗一键式攻击。如果我们对调用方进行身份验证并使用ViewState,请在Page_Init事件处理程序中设置Page.ViewStateUserKey属性,以防止一键式攻击。

void Page_Init (object sender, EventArgs e) {
  ViewStateUserKey = Session.SessionID;
}

将属性设置为我们知道每个用户唯一的值,例如会话ID,用户名或者用户标识符。

当攻击者创建一个网页(.htm或者.aspx),该网页包含一个名为__VIEWSTATE的隐藏表单域且已经填充ViewState数据时,就会发生一键式攻击。可以从攻击者先前创建的页面(例如包含100个项目的购物车页面)生成ViewState。攻击者诱使毫无戒心的用户浏览该页面,然后攻击者导致该页面被发送到ViewState有效的服务器。服务器无法知道ViewState源自攻击者。 ViewState验证和HMAC不能抵抗这种攻击,因为ViewState有效,并且页面是在用户的安全上下文下执行的。

通过设置ViewStateUserKey属性,当攻击者浏览到一个页面以创建ViewState时,该属性将初始化为他或者她的名字。当合法用户将页面提交到服务器时,将使用攻击者的名称对其进行初始化。结果,ViewState HMAC检查失败,并生成异常。

回答

ASHX文件类型的用法:
如果我们只想输出一些基本的html或者xml而无需通过页面事件处理程序,则可以以一种简单的方式实现HttpModule

将页面命名为SomeHandlerPage.ashx,然后将以下代码(仅一行)放入其中

<%@ webhandler language="C#" class="MyNamespace.MyHandler" %>

然后是代码文件

using System;
using System.IO;
using System.Web;

namespace MyNamespace
{
    public class MyHandler: IHttpHandler
    {
        public void ProcessRequest (HttpContext context)
        {   
            context.Response.ContentType = "text/xml";
            string myString = SomeLibrary.SomeClass.SomeMethod();
            context.Response.Write(myString);
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}

回答

在内容页面中为母版页启用智能感知
我敢肯定这是一个鲜为人知的骇客

大多数情况下,我们必须使用findcontrol方法并将控件从内容页投射到母版页中时,如果要使用MasterType指令,将在Visual Studio中启用intellisense。

只需向页面添加一个指令

<%@ MasterType VirtualPath="~/Masters/MyMainMasterPage.master" %>

如果我们不想使用虚拟路径,而是使用类名,则

<%@ MasterType TypeName="MyMainMasterPage" %>

在此处获取全文

回答

Page对象上的ClientScript属性。

回答

代码表达式生成器

样本标记:

Text = '<%$ Code: GetText() %>'
Text = '<%$ Code: MyStaticClass.MyStaticProperty %>'
Text = '<%$ Code: DateTime.Now.ToShortDateString() %>'
MaxLenth = '<%$ Code: 30 + 40 %>'

代码表达式生成器的真正魅力在于,我们可以在非数据绑定的情况下像表达式一样使用数据绑定。我们还可以创建执行其他功能的其他表达式生成器。

web.config:

<system.web>    
    <compilation debug="true">
        <expressionBuilders>
            <add expressionPrefix="Code" type="CodeExpressionBuilder" />

使这一切变为现实的cs类:

[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
    public override CodeExpression GetCodeExpression(
        BoundPropertyEntry entry,
        object parsedData,
        ExpressionBuilderContext context)
    {            
        return new CodeSnippetExpression(entry.Expression);
    }
}

回答

System.Web.Hosting.HostingEnvironment.MapPath

回答

machine.config级别的零售模式:

<configuration>
  <system.web>
    <deployment retail="true"/>
  </system.web>
</configuration>

覆盖web.config设置以将debug强制设置为false,打开自定义错误并禁用跟踪。在发布之前不必忘记更改属性,只需将它们全部配置为用于开发或者测试环境并更新生产零售设置即可。

回答

我想到了一个功能,有时我们需要对嘲笑者隐藏页面的某些部分。我们可以使用javascript或者使用以下简单代码来做到这一点:

if (Request.Browser.Crawler){
        HideArticleComments();

回答

GuaranteeChildControls方法:它检查子控件是否已启动。如果未启动子控件,它将调用CreateChildControls方法。

回答

我的团队经常将此作为骇客:

WebRequest myRequest = WebRequest.Create("http://www.google.com");
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream());

// here's page's response loaded into a string for further use

String thisReturn = sr.ReadToEnd().Trim();

它将网页的响应作为字符串加载。我们也可以发送post参数。

当我们需要便宜又快速的东西时,我们用它代替ASCX / AJAX / WebServices。基本上,这是跨服务器访问Web可用内容的快速方法。实际上,我们昨天才将其称为"乡下人Web服务"。

回答

这是最好的。将此添加到web.config中,以更快地进行编译。这是通过此QFE发布的3.5SP1.

<compilation optimizeCompilations="true">
Quick summary: we are introducing a
  new optimizeCompilations switch in
  ASP.NET that can greatly improve the
  compilation speed in some scenarios. 
  There are some catches, so read on for
  more details.  This switch is
  currently available as a QFE for
  3.5SP1, and will be part of VS 2010.
  
  The ASP.NET compilation system takes a
  very conservative approach which
  causes it to wipe out any previous
  work that it has done any time a ‘top
  level’ file changes. ‘Top level’ files
  include anything in bin and App_Code,
  as well as global.asax. While this
  works fine for small apps, it becomes
  nearly unusable for very large apps.
  E.g. a customer was running into a
  case where it was taking 10 minutes to
  refresh a page after making any change
  to a ‘bin’ assembly.
  
  To ease the pain, we added an
  ‘optimized’ compilation mode which
  takes a much less conservative
  approach to recompilation.

通过这里:

回答

WebMethods。

我们可以将ASP.NET AJAX回调用于放置在ASPX页面中的Web方法。我们可以使用[WebMethod()]和[ScriptMethod()]属性来装饰静态方法。例如:

[System.Web.Services.WebMethod()] 
[System.Web.Script.Services.ScriptMethod()] 
public static List<string> GetFruitBeginingWith(string letter)
{
    List<string> products = new List<string>() 
    { 
        "Apple", "Banana", "Blackberry", "Blueberries", "Orange", "Mango", "Melon", "Peach"
    };

    return products.Where(p => p.StartsWith(letter)).ToList();
}

现在,在ASPX页面中,我们可以执行以下操作:

<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
        <input type="button" value="Get Fruit" onclick="GetFruit('B')" />
    </div>
</form>

并使用以下代码通过JavaScript调用服务器端方法:

<script type="text/javascript">
    function GetFruit(l)
    {
        PageMethods.GetFruitBeginingWith(l, OnGetFruitComplete);
    }

    function OnGetFruitComplete(result)
    {
        alert("You got fruit: " + result);
    }
</script>

回答

ASP.NET的一项鲜为人知且很少使用的功能是:

标签映射

它很少使用,因为在特定情况下我们需要它,但是当我们需要它时,它非常方便。

有关此鲜为人知的功能的一些文章:

ASP.NET中的标签映射
在ASP.NET 2.0中使用标签映射

从上一篇文章中得出:

Tag mapping allows you to swap
  compatible controls at compile time on
  every page in your web application. A
  useful example is if you have a stock
  ASP.NET control, such as a
  DropDownList, and you want to replace
  it with a customized control that is
  derived from DropDownList. This could
  be a control that has been customized
  to provide more optimized caching of
  lookup data. Instead of editing every
  web form and replacing the built in
  DropDownLists with your custom
  version, you can have ASP.NET in
  effect do it for you by modifying
  web.config:
<pages>
 <tagMapping>
   <clear />
   <add tagType="System.Web.UI.WebControls.DropDownList"
        mappedTagType="SmartDropDown"/>
  </tagMapping>
</pages>

回答

Request.IsLocal属性:

它指示当前请求是否来自本地计算机。

if( Request.IsLocal )
{
   LoadLocalAdminMailSettings();
}
else
{
   LoadServerAdminMailSettings();
}

回答

面板中的DefaultButton属性。

它为特定面板设置默认按钮。

回答

Page指令中的MaintenanceScrollPositionOnPostback属性。它用于维护aspx页面在回发中的滚动位置。

回答

在开始长时间运行的任务之前,请检查客户端是否仍处于连接状态:

if (this.Response.IsClientConnected)
{
  // long-running task
}

回答

与optimizeCompilations = true解决方案类似,这里还有另一个解决方案可以加快我们在两次构建之间等待的时间(非常好,尤其是在处理大型项目时):创建基于ram的驱动器(即使用RamDisk)并更改默认的临时ASP.NET文件到此基于内存的驱动器。

有关如何执行此操作的完整详细信息,请访问我的博客:http://www.wagnerdanda.me/2009/11/speeding-up-build-times-in-asp-net-with-ramdisk/

基本上,我们首先要配置一个RamDisk(同样,在我的博客中有一个指向免费ramdisk的链接),然后我们根据以下内容更改web.config:

<system.web>
 ....
     <compilation debug="true" tempDirectory="R:\ASP_NET_TempFiles\">
     ....
     </compilation>
 ....
 </system.web>

这大大增加了我的开发时间,我们只需要为计算机投资内存即可:)

编程愉快!

瓦格纳·丹达(Wagner Danda)

回答

我们是否知道可以在IIS或者Visual Studio外部运行ASP.Net?

整个运行时已打包,可以随时托管在任何想要尝试的过程中。使用ApplicationHostHttpRuntimeHttpApplication类,我们也可以研磨这些.aspx页并从中获取闪亮的HTML输出。

HostingClass host = ApplicationHost.CreateApplicationHost(typeof(HostingClass), 
                                            "/virtualpath", "physicalPath");
host.ProcessPage(urlToAspxFile);

和托管类:

public class HostingClass : MarshalByRefObject
{
    public void ProcessPage(string url)
    {
        using (StreamWriter sw = new StreamWriter("C:\temp.html"))
        {
            SimpleWorkerRequest worker = new SimpleWorkerRequest(url, null, sw);
            HttpRuntime.ProcessRequest(worker);
        }
                    // Ta-dah!  C:\temp.html has some html for you.
    }
}

回答

如果使用Web服务而不是WCF服务,则仍可以使用标准.Net成员身份来强制执行身份验证和登录会话行为
在一套Web服务上的方式类似于我们如何通过成员身份验证和无需特殊会话来保护网站的方式
和/或者soap标头实现,只需在调用后简单地调用System.Web.Security.FormsAuthentication.SetAuthCookie(userName,false)
Membership.ValidateUser(当然是用户名,密码),以在响应中创建cookie,就像用户已通过Web表单登录一样。
然后,我们可以使用Response.Cookies []。Value检索此身份验证cookie,并将其作为字符串返回给用户。
通过提取以下代码在Application_BeginRequest中重新创建cookie,可用于在后续调用中对用户进行身份验证
cookie方法从Request.InputStream调用参数,并在成员资格以这种方式对请求进行身份验证之前重新创建auth cookie。
成员资格提供者被欺骗,将知道请求已通过身份验证并执行所有规则。

将此Cookie返回给用户的示例Web方法签名为:
字符串登录名(用户名,密码)

后续的网络方法调用示例为:
字符串DoSomething(字符串authcookie,字符串methodParam1,int methodParam2等),我们需要从Request.InputStreamis中提取authcookie(这是从Login方法获得的值)参数。

这还将模拟一个登录会话并在Web方法中调用FormsAuthentication.SignOut,例如Logout(authcookie)
使用户需要再次登录。

回答

许多人提到重新编译时如何优化代码。最近,我发现我可以在aspx页面中完成大部分开发工作(代码隐藏的东西),而完全跳过了构建步骤。只需保存文件并刷新页面即可。我们所要做的就是将代码包装在以下标记中:

<script runat="server">

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     Response.Write("Look Ma', I didn't even had to build!")
   End Sub

</script>

完成后,只需将所有内容移至后台代码,构建,测试一切正常,瞧!

-D

回答

我在多个版本的VB,VBScript和VB.NET上使用的功能之一是将记录集值转换为字符串,从而消除了对NULL或者空白的多重测试。即Trim(rsData(" FieldName")。Value&"")
如果是整数值,则应为:CLng(" 0"&Trim(rsData(" FieldName")。Value&""))`

回答

在网站发布并部署到生产服务器中之后,如果需要在服务器端单击事件上进行一些更改。我们可以使用aspx页面本身中的new关键字来覆盖现有的click事件。

例子

方法背后的代码

Protected void button_click(sender object, e System.EventArgs) 
  {
     Response.Write("Look Ma', I Am code behind code!")  
  }

过度使用方法:

<script runat="server">   
   Protected void new button_click(sender object, e System.EventArgs) 
  {
     Response.Write("Look Ma', I am overrided method!")  
  }

</script

这样,我们无需重新部署即可轻松修复生产服务器错误。

回答

使用configSource拆分配置文件。

我们可以在web.config文件中使用configSource属性将配置元素推送到其他.config文件,例如,
代替:

<appSettings>
        <add key="webServiceURL" value="https://some/ws.url" />
        <!-- some more keys -->
    </appSettings>

...我们可以将整个appSettings部分存储在另一个配置文件中。这是新的web.config

<appSettings configSource="myAppSettings.config" />

myAppSettings.config文件:

<appSettings>        
        <add key="webServiceURL" value="https://some/ws.url" />
        <!-- some more keys -->
    </appSettings>

对于我们将应用程序部署到客户并且我们不希望他们干扰web.config文件本身并且只希望他们仅能更改一些设置的情况,这是非常有用的。

参考:http://weblogs.asp.net/fmarguerie/archive/2007/04/26/using-configsource-to-split-configuration-files.aspx

回答

应用程序变量可以与Web应用程序一起使用,以在整个应用程序之间进行通信。它在Global.asax文件中初始化,并且所有用户独立于他们创建的会话在该Web应用程序的页面上使用。

回答

web.config中appsettings元素上的"文件"属性。

指定包含自定义应用程序配置设置的外部文件的相对路径。

如果我们需要在不同环境(产品)上进行修改的应用程序设置中只有很少的应用程序设置,那么这是绝佳的选择。

由于对Web.config文件的任何更改都会导致应用程序重新启动,因此使用单独的文件允许用户修改appSettings部分中的值,而不会导致应用程序重新启动。单独文件的内容与Web.config文件中的appSettings部分合并。