You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Web Razor Pages(.NET8)无法读取SQL数据库数据求助

问题描述

使用ASP.NET Web Razor Pages(.NET8)开发Clients页面,现有两个文件:

视图文件(Index.cshtml)

@page
@model AfterFix.Pages.Clients.IndexModel
@{}
@using System.Collections.Generic; 

<br>
<h2>List of Clients</h2>
<a class='btn btn-primary btn-sm' href='/Clients/Create'>New Client</a>
<table class="table"> 
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Address</th>
            <th>Created At</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    @foreach(var item in Model.listclients)
        {
            <tr>
                <td>@item.id</td>
                <td>@item.name</td>
                <td>@item.email</td>
                <td>@item.phone</td>
                <td>@item.address</td>
                <td>@item.created_at</td>
                <td>
                    <a class="btn btn-primary btn-sm" href="/Clients/Edit?id=@item.id">Edit</a>
                    <a class="btn btn-primary btn-sm" href="/Clients/Delete?id=@item.id">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

PageModel文件(Index.cshtml.cs)

using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Data.SqlClient;

namespace AfterFix.Pages.Clients
{
    public class IndexModel : PageModel
    {
        public List<ClientInfo> listclients = new List<ClientInfo>();
        public void OnGet()
        {
            try
            {
                 string connectionString = "Data Source=.\sqlexpress;Initial Catalog=mystore;Integrated Security=True;Encrypt=True;Trust Server Certificate=True";
                   using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    string sql = "SELECT * From clients";
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                ClientInfo clientInfo = new ClientInfo();
                                clientInfo.id = "" + reader.GetInt32(0);
                                clientInfo.name = reader.GetString(1);
                                clientInfo.email = reader.GetString(2);
                                clientInfo.phone = reader.GetString(3);
                                clientInfo.address = reader.GetString(4);
                                clientInfo.created_at = reader.GetDateTime(5).ToString();
                                listclients.Add(clientInfo);
                            }
                        }
                    }

                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Exception : " + ex.ToString());
            }

        }
    }
    public class ClientInfo
    {
        public string id;
        public string name;
        public string email;
        public string phone;
        public string address;
        public string created_at;
    }
}

项目可正常运行,但无法显示SQL数据库中的数据;修改连接字符串后无任何变化,怀疑程序未读取数据库,询问是否需要添加其他文件实现数据展示。


解决方案

不需要添加额外文件,问题出在连接字符串、异常处理或数据库验证环节,按以下步骤排查修复:

1. 修复连接字符串转义错误

代码中连接字符串的.\sqlexpress反斜杠未转义,C#中会被解析为无效转义字符,直接导致数据库连接失败。修改为以下两种写法之一:

// 写法1:使用@符号避免转义
string connectionString = @"Data Source=.\sqlexpress;Initial Catalog=mystore;Integrated Security=True;Encrypt=True;Trust Server Certificate=True";

// 写法2:手动转义反斜杠
string connectionString = "Data Source=.\\sqlexpress;Initial Catalog=mystore;Integrated Security=True;Encrypt=True;Trust Server Certificate=True";

2. 优化异常捕获,显示错误信息

当前异常仅输出到控制台,网页无法看到错误细节,导致无法定位问题。修改PageModel添加错误信息属性,并在视图显示:

修改PageModel

public class IndexModel : PageModel
{
    public List<ClientInfo> listclients = new List<ClientInfo>();
    // 添加错误信息属性
    public string ErrorMessage { get; set; } = "";

    public void OnGet()
    {
        try
        {
            // 使用修复后的连接字符串
            string connectionString = @"Data Source=.\sqlexpress;Initial Catalog=mystore;Integrated Security=True;Encrypt=True;Trust Server Certificate=True";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                string sql = "SELECT * From clients";
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            ClientInfo clientInfo = new ClientInfo();
                            clientInfo.id = "" + reader.GetInt32(0);
                            clientInfo.name = reader.GetString(1);
                            clientInfo.email = reader.GetString(2);
                            clientInfo.phone = reader.GetString(3);
                            clientInfo.address = reader.GetString(4);
                            clientInfo.created_at = reader.GetDateTime(5).ToString();
                            listclients.Add(clientInfo);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // 将异常信息赋值给属性,在网页显示
            ErrorMessage = "数据库访问失败:" + ex.Message;
        }
    }
}

修改视图(Index.cshtml)

在<h2>标签下方添加错误提示区域:

<h2>List of Clients</h2>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
    <div class="alert alert-danger">@Model.ErrorMessage</div>
}
<a class='btn btn-primary btn-sm' href='/Clients/Create'>New Client</a>

3. 验证数据库与表的正确性

  • 确认SQL Server Express服务处于运行状态
  • 确认mystore数据库存在,且clients表的字段顺序与代码读取顺序一致(第0列是int类型的id,第1列是name,以此类推)
  • 确认clients表中存在数据

4. 规范连接字符串配置(可选)

推荐将连接字符串放到appsettings.json中,便于修改和维护:

  1. 在项目根目录创建appsettings.json文件,内容:
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.\\sqlexpress;Initial Catalog=mystore;Integrated Security=True;Encrypt=True;Trust Server Certificate=True"
  }
}
  1. 修改PageModel通过依赖注入读取配置:
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;

namespace AfterFix.Pages.Clients
{
    public class IndexModel : PageModel
    {
        private readonly IConfiguration _configuration;
        public List<ClientInfo> listclients = new List<ClientInfo>();
        public string ErrorMessage { get; set; } = "";

        // 构造函数注入IConfiguration
        public IndexModel(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public void OnGet()
        {
            try
            {
                // 从配置文件读取连接字符串
                string connectionString = _configuration.GetConnectionString("DefaultConnection");
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    // 后续数据库操作不变
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "数据库访问失败:" + ex.Message;
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者hhaannyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 03:19:52