如何解决Asp.net Core MVC Index的可选参数
im当前正在尝试在ASP.net核心mvc中使用可选参数“ id”创建一个Controller。 我对asp.net相当陌生,我尝试检查其他帖子,但没有任何解决方案。
public class TestController : Controller
{
private readonly ITestRepository _TestRepository;
public TestController(ITestRepository TestRepository)
{
_TestRepository = TestRepository;
}
public async Task<IActionResult> Index(string id)
{
if (string.IsNullOrEmpty(id))
{
return View("Search");
}
var lieferscheinInfo = await _TestRepository.GetTestdata(Convert.ToInt64(id));
if (lieferscheinInfo == null)
{
// return err view
throw new Exception("error todo");
}
return View(lieferscheinInfo);
}
}
我想像“ localhost:6002 / Test”或“ localhost:6002 / Test / 123750349”这样打开站点,例如,参数也可以是int,我已经尝试过(string和int),但是它不起作用。
网站要么返回404(对于两种情况,无论是否有参数),要么该参数被忽略并且始终为null。
我试图在索引上添加[Route("{id?}")]
,但它没有任何改变。
问候
解决方法
在项目的Startup类中,确保使用正确的MapControllerRoute
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",pattern: "{controller=Test}/{action=Index}/{id?}");
});
,
您的代码应该可以正常工作。字符串参数默认情况下接受null,因此您无需指定可以检查在startup.cs文件中如何设置路由。
您可以通过以下属性添加路由:
[Route("Test")]
[Route("Test/Index")]
[Route("Test/Index/{id?}")]
将允许您使用:
/test/?id=sasasa
test/Index/?id=sasasa
test/Index
在Microsoft网站上查看“路由文档”: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1
,在Startup.cs中更新MapControllerRoute
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name : "default",pattern: "{controller=Test}/{action=Index}/{id?}"
);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。