检查 asp.net 中的第二个参数

check second parameter in asp.net

我是 c# mvc 的新手,我正在尝试创建一个包含多个参数的路由,如下所示:

controller/action/parameterOne/parameterTwo

但在某些情况下,我将只使用其中之一,因此路线将如下所示:

controller/action/parameterOne

这是我的 RouteConfig.cs

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name:"Default2",
            url: "{controller}/{action}/{category}/{id}",
            defaults: new { controller = "Home", action = "Index", category = UrlParameter.Optional, id = UrlParameter.Optional }
        );
    }

现在在我的控制器的操作中,我需要检查是否只有一个或两个参数,这样我就可以 return 每个条件的不同视图,这是控制器:

[HttpGet]
    public ActionResult someAction(string category, string id)
    {
        if (String.IsNullOrWhiteSpace(id))
        {
                return View("viewOne");
        }
        else
        {
            return View("ViewTwo");
        }
    }

问题是 if 语句没有完全正常工作?因为如果条件是这样的:String.IsNullOrWhiteSpace(id)

如果我写 controller/action/parameterOne 这个 return ViewOne

但如果我写 controller/action/parameterOne/parameterTwo 也 return ViewOne

但现在如果反转条件并且我写 !String.IsNullOrWhiteSpace(id) 两个 url return ViewTwo.

那么有人知道为什么会这样吗?

您是否反对只使用默认路由?想到的唯一缺点是,如果您真的希望 url 以某种方式显示,在这种情况下,您可能需要定义多条路线。但是,以下内容仅适用于默认路由:

//note controller actions will default to HttpGet if no data annotation is explicitly supplied. Also, action names generally begin uppercase by convention
public ActionResult SomeAction(string category, string id = null)
{
    if (String.IsNullOrWhiteSpace(id))
    {
        return View("viewOne");
    }
    else
    {
        return View("ViewTwo");
    }
}

您提到的各种请求如下所示:

www.myhost.com/controller/someaction?类别=参数一&id=参数二

www.myhost.com/controller/someaction?category=parameterOne