我是C#的超级新手,我不知道自己在做什么.我得到了一个任务,将C#后端与本地SQL服务器一起使用,并将数据获取/发布到数据库中.

我一直在学习教程,直到我try 从SQL表中获取数据时遇到问题:


System.NotSupportdException:不支持序列化和反序列化""System.Type""实例.路径:$.Columns.DataType. ->System.NotSupportdException:不支持序列化和反序列化""System.Type""实例." 在System.Text.Json.Serialization.Converters.UnsupportedTypeConverter1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) at System.Text.Json.Serialization.JsonConverter1.TryWrite(Utf8JsonWriter编写器、T&A;值、JsonSerializerOptions、WriteStack&A;状态) 在System.Text.Json.Serialization.Metadata.JsonPropertyInfo1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer) at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryWrite(Utf8JsonWriter编写器、T值、JsonSerializerOptions、WriteStack&A;状态) 在System.Text.Json.Serialization.JsonConverter1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state) at System.Text.Json.Serialization.JsonConverter1.TryWriteAsObject(Utf8JsonWriter编写器、对象值、JsonSerializerOptions、WriteStack&A;状态) 在System.Text.Json.Serialization.JsonConverter1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state) at System.Text.Json.Serialization.Converters.IEnumerableConverter1.OnWriteResume(Utf8JsonWriter编写器、T集合值、JsonSerializerOptions、WriteStack&A;状态) 在System.Text.Json.Serialization.JsonCollectionConverter2.OnTryWrite(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, WriteStack& state) at System.Text.Json.Serialization.JsonConverter1.TryWrite(Utf8JsonWriter编写器、T&A;值、JsonSerializerOptions、WriteStack&A;状态) 在System.Text.Json.Serialization.Metadata.JsonPropertyInfo1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer) at System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryWrite(Utf8JsonWriter编写器、T值、JsonSerializerOptions、WriteStack&A;状态) 在System.Text.Json.Serialization.JsonConverter1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state) at System.Text.Json.Serialization.JsonConverter1.WriteCore(Utf8JsonWriter编写器、T&A;值、JsonSerializerOptions、WriteStack&A;状态) -内部异常堆栈跟踪结束 在System.Text.Json.ThrowHelper.ThrowNotSupportedException(WriteStack&状态下,不支持异常(Ex) 在System.Text.Json.Serialization.JsonConverter1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state) at System.Text.Json.Serialization.JsonConverter1.WriteCoreAsObject(Utf8JsonWriter编写器、对象值、JsonSerializerOptions、WriteStack&A;状态) 在System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter、Utf8JsonWriter、TValue&Value、JsonSerializerOptions、WriteStack&状态) At System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json,TValue Value,JsonTypeInfo jsonTypeInfo,CancerationToken ancellationToken) At System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json,TValue Value,JsonTypeInfo jsonTypeInfo,CancerationToken ancellationToken) At System.Text.Json.JsonSerializer.WriteStreamAsync[TValue](Stream utf8Json,TValue Value,JsonTypeInfo jsonTypeInfo,CancerationToken ancellationToken) 在Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.ExecuteAsync(ActionContext上下文中,JsonResult结果) At Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|30_0[TFilter,TFilterAsync](资源调用器调用器,任务最后任务,下一个状态,作用域,对象状态,布尔值已完成) 在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed环境中) 在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,T筛选器异步](状态&A;下一个、作用域&A;范围、对象&A;状态、布尔值&A;已完成) 在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() -来自前一位置的堆栈结束跟踪 在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker调用方,任务最后任务、状态下一个、作用域、对象状态、布尔值isComplete) 在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker调用方,任务任务,IDisposable作用域) 在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker调用方,任务任务,IDisposable作用域) 在Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint终结点,任务请求任务、日志(log)记录器) 在Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext环境中) 在Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext HttpContext上) 在Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext http上下文中,iswaggerProvider swaggerProvider) 在Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext环境中)

国家元首和政府首脑

接受度:/

连接:保持连接

Host: localhost:5291

用户代理:PostmanRuntime/7.29.2

Accept-编码:GZIP、DEFEATE、br

postman -令牌:ad516da9-02bb-424f-8979-64365d710b2c

Error message


This is my controller

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using webApi.Models;
using Microsoft.AspNetCore.Hosting;
using System.IO;

namespace webApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ContactController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly IWebHostEnvironment _env;
        public ContactController(IConfiguration configuration, IWebHostEnvironment env)
        {
            _configuration = configuration;
            _env = env;
        }

        [HttpGet]
        public JsonResult Get()
        {
            string query = @"select ContactName from dbo.Contact";

            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("ContactAppCon");
            SqlDataReader myReader;
            using (SqlConnection myCon = new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader);
                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult(table);
        }
    }
}

This is model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace webApi.Models
{
    public class Contact
    {
        public int ContactID { get; set; }

        public string ContactName { get; set; }

        public string ContactEmail { get; set; }

        public string ContactSubject { get; set; }

        public string ContactMessage { get; set; }


   
    }
}

This is startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.FileProviders;
using System.IO;

namespace WebApplication1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Enable CORS
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });


            //JSON Serializer
            _ = services.AddControllersWithViews().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
                .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver
                = new DefaultContractResolver());

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //Enable CORS
            app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                   Path.Combine(Directory.GetCurrentDirectory(), "Photos")),
                RequestPath = "/Photos"
            });
        }
    }
}

推荐答案

这不是一个好主意:

return new JsonResult(table);

DataTable对象包含所有类型的内部工作:(1)可能不能很好地序列化;(2)您不想发送给用户.(您是否知道它doesn't在任何地方包含您的数据库连接字符串?否则,将其展示给您的用户是不明智的.)

如果你想发送给你的用户的是Contact个实例的集合,那么就发送给他们.我已经有一段时间没有直接使用ADO了,但我想它至少与此相当接近:

var result = new List<Contact>();
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
    myCon.Open();
    using (SqlCommand myCommand = new SqlCommand(query, myCon))
    {
        myReader = myCommand.ExecuteReader();
        while (myReader.Read())
        {
            result.Add(new Contact
            {
                ContactName = myReader["ContactName"].ToString()
            });
        }
        myReader.Close();
        myCon.Close();
    }
}
return new JsonResult(result);

因为您只 Select 了查询中的一列,所以我只将一列映射到结果对象.当然,如果您 Select 更多,您可以映射更多.

也可能有other ways to do it个,您可以通过使用更现代的数据库访问技术(实体框架、Dapper等)来显著减少代码量,但总体目标是将原始数据库记录映射到您的类型化对象并返回这些对象.

Csharp相关问答推荐

需要多次输入的控制台应用程序

单元测试和MOQ,最佳解决方案

C#中的两个线程之间读写浮点类型

[0-n]范围内有多少个Integer在其小数表示中至少包含一个9?

发布.NET框架项目将.NET核心元素注入到web. connect中

如何使用C#中的图形API更新用户配置文件图像

EF Core判断是否应用了AsSplitQuery()

. NET 8使用COM向VB6公开

一小时后,自定义缓存停止在App Insight中保存

为什么我的ASP.NET核心MVC应用程序要为HTML元素添加一些标识符?

如何在Windows 11任务调度程序中每1分钟重复一次任务?

未在数据流块之间传播完成

确定System.Text.Json序列化中是否无法识别Type

为什么我可以用硬编码的集合而不是变量来设置没有setter的IList属性的值?

如何在CSharp中将json字符串转换为DataTable?

C#自定义验证属性未触发IsValid方法

我找不到ASP.NET Web应用程序(.NET框架).已 Select .NET框架项目和项模板以及此组件(&Q;)

从GRPC连接创建ZipArchive

为什么在使用JsonDerivedType序列化泛型时缺少$type?

最小API定义的Swagger标头参数