c# - 属性路由不起作用并在 URL 中引发 404 错误
问题描述
我将属性路由应用于我的 RouteConfig.cs 并在 Action 上添加了 [Route("Store")] 属性,但在访问 url 时出现错误。
工作 URL 是http://localhost:52859/shop/store/dominos
我希望它更改为http://localhost:52859/store/dominos
但是发布更新属性路由后,我在页面上看到错误为
“/”应用程序中的服务器错误。运行时错误描述:处理您的请求时发生异常。此外,在执行第一个异常的自定义错误页面时发生了另一个异常。请求已终止。
在 URL 中显示为
http://localhost:52859/Errors/Error404?aspxerrorpath=/shop/store/dominos
在 RouteConfig 中更新
routes.MapMvcAttributeRoutes();
调用商店的操作
// GET: /shop/category/name
[Route("Store")]
public ActionResult Store(string name)
{
// Declare a list of Coupons
List<Coupn> coupnList;
using (ApplicationDbContext db = new ApplicationDbContext())
{
// Get store id
Store storeDTO = db.Store.Where(x => x.Slug == name).FirstOrDefault();
int storeId = storeDTO.StoreID;
ViewBag.TopDesc = storeDTO.TopDesc;
ViewBag.MainDesc = storeDTO.MainDesc;
ViewBag.StoreLogo = storeDTO.StoreLogo;
ViewBag.StoreName = storeDTO.StoreName;
// Init the list
coupnList = db.Coupns.ToArray().Where(x => x.StoreID == storeId).ToList();
// Get Store name
var coupnStore = db.Coupns.Where(x => x.StoreID == storeId).FirstOrDefault();
ViewBag.StoreName = coupnStore.StoreName;
}
// Return view with list
return View(coupnList);
}
非常感谢您的帮助。
解决方案
您需要在Controller
要使用的 URL 级别更改路由并将action
路由设置为"{name}"
. 像这样:
[Route("Store")]
public class StoreController: Controller
{
// GET: /store/name
[Route("{name}")]
public ActionResult Store(string name)
{
// Declare a list of Coupons
List<Coupn> coupnList;
using (ApplicationDbContext db = new ApplicationDbContext())
{
// Get store id
Store storeDTO = db.Store.Where(x => x.Slug == name).FirstOrDefault();
int storeId = storeDTO.StoreID;
ViewBag.TopDesc = storeDTO.TopDesc;
ViewBag.MainDesc = storeDTO.MainDesc;
ViewBag.StoreLogo = storeDTO.StoreLogo;
ViewBag.StoreName = storeDTO.StoreName;
// Init the list
coupnList = db.Coupns.ToArray().Where(x => x.StoreID == storeId).ToList();
// Get Store name
var coupnStore = db.Coupns.Where(x => x.StoreID == storeId).FirstOrDefault();
ViewBag.StoreName = coupnStore.StoreName;
}
// Return view with list
return View(coupnList);
}
}
如果您正在工作,请ASP.NET MVC
确保激活路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
);
}
如果您正在处理.Net Core
:
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env
)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
推荐阅读
- azure - Azure Yaml 管道表达式;${{}} 与 $()
- verilog - 如何在 Verilog 模拟测试台中写入 txt 日志文件
- php - 尝试回声时卷曲双重提交
- c - 使用 Scanf 输入字符指针数组,但是当我在“空格”被截断后输入字符串时
- ubuntu - (已解决)在 jetson nano 上构建 isaac SDK 示例时出错:JetPack43 未在任何 .rc 文件中定义
- php - Symfony5/Doctrine 找不到我的实体的 XML 映射文件
- r - 偏差和分数残差图
- r - 在 R 中显示 2 个栅格之间的异同
- csv - pyspark从本地加载bigquery中的数据框
- java - 模态对话后 SwingWorker 发布()和处理(列表)乱序