【问题标题】:Asp.net core mvc optional parameter for Index索引的 Asp.net core mvc 可选参数
【发布时间】:2020-12-04 08:46:10
【问题描述】:

我目前正在尝试使用可选参数“id”在 ASP.net core mvc 中创建一个控制器。 我对 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,我已经尝试过(字符串和 int)但是它不起作用。 要么站点返回 404(对于这两种情况,有和没有参数),要么参数被忽略并且始终为空。 我尝试在索引上添加[Route("{id?}")],但它没有改变任何东西。

问候

【问题讨论】:

  • Test 是控制器名称。基本上我想用可选参数调用我的控制器测试的 Index 方法

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


【解决方案1】:

在您项目的 Startup 类中,确保您使用的是正确的 MapControllerRoute

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Test}/{action=Index}/{id?}");

        });

【讨论】:

  • 我还需要做“测试/索引/”,我试过类似的东西
【解决方案2】:

您的代码应该可以正常工作。字符串参数默认接受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

【讨论】:

  • 但它不起作用,她的站点可以使用以下 url “localhost:6002/Test/Index/”调用,但我不希望在 url 中使用索引。我的路由在我的启动app.UseEndpoints(endpoints =&gt; { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Status}/{action=Index}/{id?}"); }); 中是这样设置的,这是针对另一个控制器的。我试图为我的控制器添加类似的东西,但它没有改变任何东西。
【解决方案3】:

更新 Startup.cs 中的 MapControllerRoute

app.UseEndpoints(endpoints => {
     endpoints.MapControllerRoute(
         name : "default",
         pattern: "{controller=Test}/{action=Index}/{id?}"
     );
});

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2014-08-31
    • 2014-11-10
    • 1970-01-01
    相关资源
    最近更新 更多