我是实体框架的新手,我正在编写一个基于web api的网站(连接到mssql)的问题.我一直在看似随机的错误(大多数似乎与数据库有关).这些错误最常发生在网站首次发布时,但有时会发生在自上次发布以来已有数小时的情况.选择的错误:
- 操作无效.连接已关闭.
- 已经有一个与此命令关联的打开DataReader,必须先关闭它.
- 连接没有关闭.连接的当前状态是连接.
- 在创建模型时无法查看上下文
- 基础提供商未能开启
我的上下文如下:
public class Context : DbContext
{
public Context() : base("name=DefaultConnection")
{
}
public override int SaveChanges()
{
DateTime now = DateTime.Now;
foreach (ObjectStateEntry entry in (this as IObjectContextAdapter).ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
{
if (!entry.IsRelationship)
{
IHasUpdated updated = entry.Entity as IHasUpdated;
if (updated != null)
updated.updated = now;
}
}
return base.SaveChanges();
}
public DbSet<Branch> Branches { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<User> Users { get; set; …Run Code Online (Sandbox Code Playgroud) 如果我有一个带有 UsersController 的 API,其中包含获取用户列表的方法,那么我应该返回一个空集合还是NotFound("Could not get the list of the users")在找不到用户时返回一个集合?
我读过很多关于返回空列表或 null 的内容,大多数答案都说我应该返回预期的内容。如果需要一个列表,则应返回一个空列表而不是 null。
但这是否也意味着 Web API 呢?
Id | StName | Subject |
1 | Tom | Math |
2 | Jerry | Science |
Run Code Online (Sandbox Code Playgroud)
我是 LINQ 新手,我试图使用 LINQ 从数据库中仅获取IdJerry StName ,但我做不到。
Id | StName | Subject |
1 | Tom | Math |
2 | Jerry | Science |
Run Code Online (Sandbox Code Playgroud)
但我得到了所有的数据。我想获取最新记录的id(仅id)。
我有一个 API (asp net core 3.1) 和一个 Web 应用程序 (asp net Blazor WebAssembly)。在我的 API 中,我有一个 CustomerController,其 POST 方法如下:
[HttpPost]
public async
Task<ActionResult>
CreateOrderAsync(OrderDto orderDto)
{
orderDto.IdOrder =
await repository
.CreateOrderAsync(mapper.Map<Order>(orderDto));
return CreatedAtRoute(nameof(GetOrderByIdAsync),
new { idOrder = orderDto.IdOrder }, orderDto);
}
Run Code Online (Sandbox Code Playgroud)
在我的 Web 应用程序中,我有 DataServiceHelper 类,我在 Web 应用程序的实际数据服务中使用它。这里我有POST和GET等方法:
...
static public async Task PostAsync(HttpClient httpClient, string endpoint, T item)
{
await httpClient.PostAsJsonAsync(endpoint, item);
}
static public async Task<T> FindOneByIdAsync(HttpClient httpClient, string endpoint)
{
return await JsonSerializer.DeserializeAsync<T>
(await httpClient.GetStreamAsync(endpoint), new JsonSerializerOptions()
{ …Run Code Online (Sandbox Code Playgroud) 我想要一个具有多个 GET 的控制器,一个用于所有,一个带有 int 参数,另一个带有字符串参数。下面的例子仍然给我错误:
[ApiController]
[Route("[controller]")]
public class StudentsController : ControllerBase
{
[HttpGet]
public IEnumerable<Student> Get()
{
return GetStudents();
}
[HttpGet("{id}")]
public Student Get(int id)
{
return GetStudents().FirstOrDefault(s=> s.id == id);
}
[HttpGet("{name}")]
public Student Get(string name)
{
return GetStudents().FirstOrDefault(s=> s.name == name);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑 当前我收到以下错误
我正在使用 ASP.NET Core WebAPI,我想为名为“Item”的对象执行 CRUD。我正在使用 EF Core 来处理 SQL 数据库,并且有两个模型来代表我的对象。
我的 HTTP GET one 和 HTTP GET much 方法的工作方式如下
获取 ItemRepository 实例
获取一个或多个ItemEntity
使用 AutoMapper将其映射到ItemDto这在我的构造函数中初始化,例如
m_itemDtoMapper = new Mapper(new MapperConfiguration(cfg => cfg.CreateMap<ItemEntity, ItemDto>()));
Run Code Online (Sandbox Code Playgroud)
在我的 WebAPI 方法中,我使用以下行将其映射到 ItemDto(对于 GET 许多情况):
var itemDtos = m_itemDtoMapper.Map<IEnumerable<ItemEntity>, ICollection<ItemDto>>(items);
Run Code Online (Sandbox Code Playgroud)
这很有效,并且 AutoMapper 非常强大。我现在的问题是:
本质上,当我创建项目并创建一个功能 API(用户可以在其中创建、删除数据库中的信息等)并运行它时,我得到了可用于测试该 API 的 swagger UI。
现在我知道它有效了,我想开始在网站上实际构建页面,而不是大摇大摆。然而,即使当我尝试将 web.config 文件中的默认页面设置为我的 Index.cshtml 时,它也会变得大摇大摆。
基本上我的问题是,我该如何改变这个?
我正在尝试使用 Serilog 登录我的 ASP.NET Web API 项目之一中的 Elasticsearch,但不幸的是,我在 Kibana 中找不到日志。
public class Logger
{
private readonly ILogger _localLogger;
public Logger()
{
ElasticsearchSinkOptions options = new ElasticsearchSinkOptions(new Uri("xxx"))
{
IndexFormat = "log-myservice-dev",
AutoRegisterTemplate = true,
ModifyConnectionSettings = (c) => c.BasicAuthentication("yyy", "zzz"),
NumberOfShards = 2,
NumberOfReplicas = 0
};
_localLogger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.File(HttpContext.Current.Server.MapPath("~/logs/log-.txt"), rollingInterval: RollingInterval.Day)
.WriteTo.Elasticsearch(options)
.CreateLogger();
}
public void LogError(string error)
{
_localLogger.Error(error);
}
public void LogInformation(string information)
{
_localLogger.Information(information);
}
}
Run Code Online (Sandbox Code Playgroud)
我可以在上面指定的文件中看到日志,但在 Elasticsearch 中看不到。所以,我想知道是否有什么方法可以调试为什么无法登录 Elasticsearch?我也愿意使用其他日志框架来登录 Elasticsearch。
*Elasticsearch 的凭证和 …
我们的主要后端服务器是一个 .net 5 Web API 项目。我需要将一些 javascript 模块和 javascript 代码集成到我们的功能中。我想节省将这些模块全部重写为 C# 以便从我们的代码访问的时间。是否有任何包或方法可以完成此任务,或者我最好运行一个单独的节点服务器来实现此功能?
所有在端口 8888 上公开 .NET 6 Web API 的尝试都会失败。
我通过在 appsettings.json 中添加 url 并在 Program.cs 中配置端口,在线尝试了这些答案和各种其他文章,但没有成功。
更新: Web API 在默认端口上启动,而不是在我想要公开它的端口上启动。在 Program.cs 中配置端口时,我收到
System.InvalidOperationException:“不支持更改 URL,因为地址为只读。”
app.Run("http://localhost:8888"); // This code results in Exception above
Run Code Online (Sandbox Code Playgroud)
或者
System.NotSupportedException:“集合具有固定大小。”
app.Urls.Add("http://localhost:8888"); // The Exception above occurs after running this line of code
Run Code Online (Sandbox Code Playgroud)
运行下面的代码不会更改端口,并且 API 在默认端口上启动
builder.WebHost.ConfigureKestrel(options => options.ListenLocalhost(8888));
Run Code Online (Sandbox Code Playgroud) asp.net-web-api ×10
c# ×8
asp.net-core ×4
.net ×1
.net-core ×1
api ×1
asp.net ×1
asp.net-mvc ×1
automapper ×1
blazor ×1
javascript ×1
linq ×1
module ×1
node.js ×1
serilog ×1
swagger-ui ×1