c# - 如何验证 GET 方法中的查询字符串参数

标签 c# asp.net-mvc asp.net-core asp.net-core-mvc asp.net-mvc-routing

我构建了一个 ASP.NET Core MVC 应用程序并且我使用了默认的 MVC URL 路由:

app.UseMvc(routes =>
{
    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

我想创建用于创建和编辑用户的 GET 方法。

要创建新用户,我需要转到 url /Admin/User 并编辑现有用户 url /Admin/User/{id:int}

我试过创建这样的方法:

[HttpGet]
public async Task<IActionResult> User(int? id)
{
}

如何限制 id 参数的类型?

我只需要允许访问 /Admin/User/Admin/User/{id:int} - 但如果我尝试即 - /Admin/User/ABCD -(使用字符串作为 ID)- 也是允许的。

如果参数 ID 是另一种类型而不是数字,那么我想返回 404

最佳答案

最简单的选择是创建具有此约束的路由。请注意,如果您像这样在路由中设置所需的参数,则没有理由使 id 可为空。

[HttpGet("Admin/User")]
public async Task<IActionResult> Add()
{
}

[HttpGet("Admin/User/{id:int}")]
public async Task<IActionResult> Edit(int id) 
{
}

或者保留名为 User 的操作方法并使用:

app.UseMvc(routes =>
{
    routes.MapRoute("AdminUser", "Admin/User/{id:int}");
    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

Note that the convention-based approach doesn't differentiate between GET/POST.

或者,如果您想将所有 ID 参数设为 int,您可以像这样为整个站点配置路由:

routes.MapRoute(
    name: "defaultWithId",
    template: "{controller}/{action}/{id:int}");
routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}");

引用:Routing in ASP.NET Core

关于c# - 如何验证 GET 方法中的查询字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48844081/

相关文章:

asp.net - MVC 6 @inherit RazorPage

asp.net-mvc - 自定义助手无法正常工作

c# - 如何使用 Razor EditorFor Helper 创建一个包含 ViewBag 中的值的 TextBox

c# - 如何在 C# .NET Core 3.1 中使用网络套接字?

c# - 带有 azure keyvault 证书的 Asp.net 核心 docker 中的 Https 不起作用

asp.net-core - .NET Core API 请求与支持的文件类型不匹配

c# - asp.net 中的 Response.Write()

c# - 更新 System.Data.SQLite.dll 后 SQLite 无效的 URI

c# - 在 ASP.NET MVC2 中将 http 204 "no content"返回给客户端

c# - 添加到另一个表单上的列表框