我有一个由 React 和 Next.js 在客户端开发的网站,并从 Asp.Net core 服务器调用 API 来获取动态数据,例如产品和类别。
问题是当我请求的 URL 中有未定义的参数(需要传递给 API 来获取相关数据)时,如何重定向到 404 未找到页面。
例如,如果请求的 URL 是 https://domain/product/unique-title-of-product,则“unique-title-of-product”将传递给 API,响应的数据将显示在产品详细信息页面中。但是,如果请求的 URL 是“https://domain/product/not-existed-title”,我该如何检查并将其重定向到 404-not-found-page?
我不想将 undefined-title 传递给服务器,因为如果不处理它,它将响应 null 或 200 或 500 内部服务器错误。那么看来我必须在客户端处理 404 重定向,而无需任何服务器端交互。但是当我尝试在 next.js 中使用 404 状态代码进行重定向时,状态代码将不会反映在浏览器中。
在客户端处理此问题的最佳解决方案是什么?或者我应该在服务器端处理它?
我正尝试通过Ajax仅向控制器发送2个ID,如下所示,但是该模型完全为空。
我的视图模型非常简单,如下所示:
public class CityAreaBindingModel
{
public int CityID { get; set; }
public int AreaID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
查看:两个下拉列表,可帮助选择城市和区域
<select class="form-control" id="CityID" name="CityID">
@{
foreach (var city in ViewData["Cities"] as List<SamsungTools.Models.City>)
{
<option value="@city.ID" @(city.ID == 1 ? "selected" : "")>@city.Title</option>
}
}
</select>
<select class="form-control" id="AreaID" name="AreaID">
@{
foreach (var area in ViewData["Areas"] as List<SamsungTools.Models.Area>)
{
<option value="@area.ID" @(area.ID == 1 ? "selected" : "")>@area.Title</option>
}
}
</select>
Run Code Online (Sandbox Code Playgroud)
Ajax:将formData与视图中的两个选定ID结合使用
var cId = $('#CityID').val();
var aId = …
Run Code Online (Sandbox Code Playgroud) 在asp.net core 3.1 Web应用程序中,我有一个从BackgroundService类继承的事件监听器。为什么注入了DbContext的injectiong存储库会出错?
启动:
services.AddDbContext<DBContext>(options => {
options.UseSqlServer("...connection string...");
});
services.AddTransient<ICalStatRepo, CalStatRepo>();
services.AddTransient<IHostedService, BackgroundListener>();
Run Code Online (Sandbox Code Playgroud)
存储库:
public class CalStatRepo : ICalStatRepo
{
private readonly DBContext _context;
public CalStatRepo(DBContext context)
{
_context = context;
}
public async Task InsertCallStat(RawCallStatRegisterViewModel model)
{
var rawCall = new RawCallStat
{
HappenedAt = model.HappenedAt,
Source = model.Source,
Destination = model.Destination,
Status = model.Status
};
_context.Entry(rawCall).State = EntityState.Added;
try
{
await _context.SaveChangesAsync();
}
catch (Exception e)
{
throw new Exception("Insert new call stat fails with this …
Run Code Online (Sandbox Code Playgroud) 如果我必须在许多查询中使用相同的条件,是否有办法编写类似表达式的内容并在所有查询中使用它?
例如:
查询1:
Context.Products.Where(p => p.active && !p.deleted && !p.hidden && //other conditions)
Run Code Online (Sandbox Code Playgroud)
查询2:
Context.Products.Where(p => p.active && !p.deleted && !p.hidden && //other conditions)
Run Code Online (Sandbox Code Playgroud)
查询3:
Context.Products.Where(p => p.active && !p.deleted && !p.hidden && //other conditions)
Run Code Online (Sandbox Code Playgroud)
所有查询中都使用重复的条件:
p.active && !p.deleted && !p.hidden
那么,如果我可以将它们编写一次并用于每个查询,例如:
条件(方法、表达式或...)= p.active && !p.deleted && !p.hidden
Context.Products.Where(p => 条件 && //其他条件)
任何想法?