c# - 带有实体框架的 Blazor webassembly 失败,并显示“不支持 ContentType;支持的类型是 'application/json'”
问题描述
这是一个简单的 CRUD 应用程序,我用来学习它是如何工作的。我以前使用过实体框架,但对它的工作原理知之甚少。这个应用程序有一个带有一个表的数据库Employee
,有 6 个常用类型列。我下载了之前编写的同一应用程序的工作副本System.Text.Json
,因此数据库连接正常。
来电GetEmployee.razor
是:
@code {
private Employee[] empList;
protected override async Task OnInitializedAsync()
{
try
{
empList = await Http.GetFromJsonAsync<Employee[]>("/api/Employee/Index");
}
catch (Exception ex)
{
string foo = ex.ToString();
}
}
}
namespace Clean.Server.Api
{
public partial class ManagementContext : DbContext
{
public ManagementContext()
{
}
public ManagementContext(DbContextOptions<ManagementContext> options)
: base(options)
{
}
public virtual DbSet<Employee> Employee { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=MtLyell\\SQLEXPRESS;Database=Management;Integrated Security=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>(entity =>
{
entity.Property(e => e.Designation)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.Email)
.HasMaxLength(20)
.IsUnicode(false);
entity.Property(e => e.Location)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
amespace Clean.Server.Api
{
public partial class Employee
{
public long EmployeeId { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
public string Email { get; set; }
public string Location { get; set; }
public long PhoneNumber { get; set; }
}
}
namespace Clean.Server.Api
{
public interface IEmployeAccessLayer
{
IEnumerable<Employee> GetAllEmployees();
void AddEmployee(Employee employee);
void UpdateEmployee(Employee employee);
Employee GetEmployeeData(long id);
void DeleteEmployee(long id);
}
public class EmployeAccessLayer : IEmployeAccessLayer
{
private ManagementContext _context;
public EmployeAccessLayer(ManagementContext context)
{
_context = context;
}
//To Get all employees details
public IEnumerable<Employee> GetAllEmployees()
{
try
{
return _context.Employee.ToList();
}
catch(Exception ex)
{
throw;
}
}
//To Add new employee record
public void AddEmployee(Employee employee)
{
try
{
_context.Employee.Add(employee);
_context.SaveChanges();
}
catch
{
throw;
}
}
//To Update the records of a particluar employee
public void UpdateEmployee(Employee employee)
{
try
{
_context.Entry(employee).State = EntityState.Modified;
_context.SaveChanges();
}
catch
{
throw;
}
}
//Get the details of a particular employee
public Employee GetEmployeeData(long id)
{
try
{
Employee employee = _context.Employee.Find(id);
return employee;
}
catch
{
throw;
}
}
//To Delete the record of a particular employee
public void DeleteEmployee(long id)
{
try
{
Employee emp = _context.Employee.Find(id);
_context.Employee.Remove(emp);
_context.SaveChanges();
}
catch
{
throw;
}
}
}
}
namespace Clean.Server.Controllers
{
public class EmployeeController : ControllerBase
{
IEmployeAccessLayer _employee;
public EmployeeController(IEmployeAccessLayer employee)
{
_employee = employee;
}
[HttpGet]
[Route("api/Employee/Index")]
public IEnumerable<Employee> Index()
{
return _employee.GetAllEmployees();
}
[HttpPost]
[Route("api/Employee/Create")]
public void Create([FromBody] Employee employee)
{
if (ModelState.IsValid)
this._employee.AddEmployee(employee);
}
[HttpGet]
[Route("api/Employee/Details/{id}")]
public Employee Details(int id)
{
return _employee.GetEmployeeData(id);
}
[HttpPut]
[Route("api/Employee/Edit")]
public void Edit([FromBody]Employee employee)
{
if (ModelState.IsValid)
this._employee.UpdateEmployee(employee);
}
[HttpDelete]
[Route("api/Employee/Delete/{id}")]
public void Delete(int id)
{
_employee.DeleteEmployee(id);
}
}
}
更完整的错误信息是:
不支持提供的 ContentType;支持的类型是 'application/json' 和结构化语法后缀 'application/+json'
要将实体对象转换为 Json,JsonSerializer.Serialize()
我尝试将其GetAllEmployees
应用于EmployeeAccessLayer.cs
. 结果是:
无法将类型字符串隐式转换为 System.Collections.Generic.IEnumerable
我最终可能会弄清楚如何做到这一点。
return JsonSerializer.Serialize(_context.Employee.ToList());
序列化是EmployeeAccessLayer.cs
在正确的想法和地方进行这种转换吗?
如果是这样,我如何将其转换为正确的类型?
或者 EF 中是否有可以为我做的设置?
解决方案
在 Startup.cs 我需要注册 ManagementContext 和 IemployeAccessLayer 我做了:
public static string Connection { get; set; }
Connection = Configuration.GetConnectionString("EmployeeDatabase");
services.AddDbContext<ManagementContext>(options => options.UseSqlServer(Connection));
services.AddScoped<IEmployeAccessLayer, EmployeAccessLayer>();
在 ManagementContext.cs 中我更改了 OnConfiguring:
optionsBuilder.UseSqlServer(Clean.Server.Startup.Connection);
在 razor 文件中似乎有效(最少测试)的 json 命令是:GetFromJsonAsync、PutAsJsonAsync、DeleteAsync、PostAsJsonAsync
推荐阅读
- git - 如何在不重复避免变基的情况下挑选提交?
- c# - 如何在 JSON 中创建数组?
- google-api - 无法从 App Center 连接到 Google Play 以分发 App
- c++ - C ++通过结构数组搜索值
- firebase - Firebase 云功能最佳实践?
- javascript - 为什么在弗雷德弗林斯顿之后警报显示未定义?ES6 中的“const”有哪些属性?
- machine-learning - 不平衡数据集的标记化
- css - 在 body 旁边放一个元素
- reactjs - 找不到 react-redux 上下文值;请确保组件被包裹在一个
- angular - 如何在不取消订阅的情况下通过 Angular HttpClient 发送 POST 请求?