gpt4 book ai didi

asp.net-mvc - 当 id 为 null 时,ASP.NET MVC 抛出错误

转载 作者:行者123 更新时间:2023-12-02 00:22:03 24 4
gpt4 key购买 nike

我有一个公开可用的 Controller (操作不能隐藏在任何安全属性下)。 Controller 也有一个公开可用的操作。

以下是 Controller 的示例结构:

 public SomeController : Controller {


[HttpGet]
public ActionResult show(int id){

}

}

该操作有一个必需的 id 字段。然而,当有人输入格式错误的 URL 而没有所需的 id 时(或者当搜索引擎机器人使用所需的 id 访问 URL 时),会抛出一个不必要地添加到日志中的错误。

处理这个解决方案的理想方案应该是什么。

我想到的可能的解决方案是:

  • 将 id 设置为 Nullable (int?id) 并通过将调用者重定向到显示适当错误的其他页面来显式处理没有值的情况
  • 显式发送 404 错误

是否有使用属性来执行此操作的通用方法?

P.S:(具体而言)我的意思是写 if else 条件来处理每个 Controller 的此类情况。

如果有任何正确方向的提示,我将不胜感激。

最佳答案

你需要一个路由约束。这将有助于路由器更早地抛出 URL(导致 404)而不是更晚地抛出 URL(路由有效,转到操作,操作 barfs 因为缺少参数)。

http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs

示例默认路由(可能替换 global.asax.cx 中的现有路由):

// order is important; more specific routes to less specific routes is what you want
//
// default index action, with no ID
routes.MapRoute(
"Default_Index",
"{controller}/",
new {controller="Home", action="Index"}
);

// default create action, with no ID
routes.MapRoute(
"Default_Create",
"{controller}/Create",
new {controller="Home", action="Create"}
);

// default action requiring an ID (such as EDIT)
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller="Home", action="Index"},
new {id = @"\d+" }
);

关于asp.net-mvc - 当 id 为 null 时,ASP.NET MVC 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10511676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com