web.config文件中的命名空间不起作用

本文关键字:命名空间 不起作用 config 文件 web | 更新日期: 2023-09-27 18:09:54

可能重复:
如何在web.config文件中添加命名空间?

我正在尝试在web.config文件中添加名称空间,以便在所有网页中使用它(在code behind中(。但它不起作用
有人试过吗?我以前问过这个问题,但没有得到合适的答案。
为了更好地理解这里是code behind文件

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWeb
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.BackColor = Color.Red;// It is not working.
        }
    }
}

这是web.config文件

<?xml version="1.0"?>
<configuration>
  <system.web>
    <pages>
      <namespaces>
        <clear/>
        <add namespace="System.Drawing" />
      </namespaces>
    </pages>
  </system.web>
</configuration>

编辑

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestWeb._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load(object sender, EventArgs e)
    {
        Label1.BackColor = Color.Red;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:label ID="Label1" runat="server" text="Label"></asp:label>
    </div>
    </form>
</body>
</html>

web.config文件中的命名空间不起作用

<namespaces>元素仅适用于aspx页面。

与VB.Net不同,C#没有在普通代码文件中自动包含名称空间的机制。

您应该先试试这个,然后再试试。

<configuration>
  <system.web>
    <pages>
      <namespaces>
        <clear/>
        <add namespace="System.Drawing" />
        <add namespace="System" />
      </namespaces>
    </pages>
  </system.web>
</configuration>

命名空间配置部分用于页面,而不是代码隐藏。代码隐藏文件在其内部表示所有命名空间导入。配置中包含的命名空间将包含在从.aspx页面生成的动态类中。

正如SLaks所说,这是行不通的。如果您正在寻找一个始终包含命名空间的快捷方式,请考虑编辑默认的VS模板,以便在创建新模板时它始终存在。