查询字符串为空时重定向
Redirecting when the querystring is empty
在我的项目中,我有两个控制器用于公交服务,公交路线和公交路线停靠站。为了访问路线站点,您需要 select 一条公交路线,如果一条路线尚未 selected,我需要重定向回公交路线索引。我做了一个 If else 语句来检查查询字符串和保存信息的 cookie。
当我直接去巴士路线站控制器时,它应该让我回到巴士路线列表,但它没有。
public ActionResult Index()
{
string busRouteCode = "";
//checks query string to see if empty
if (Request.QueryString == null)
{
//checks the cookies to see if empty
if (Request.Cookies["busRouteCode"] == null)
{
//if empty returns to bus route controller.
return View("index", "snBusRoutes");
}
else
{
busRouteCode = Response.Cookies["busRouteCode"].Value;
}
}
else
{
busRouteCode = Request.QueryString["busRouteCode"];
}
var routeStops = db.routeStops.Include(r => r.busRoute).Include(r => r.busStop);
return View(routeStops.ToList());
}
我不认为 Request.QueryString
完全 会成为 null。尽管特定的 value 可能为 null 或空。像这样:
if (string.IsNullOrWhiteSpace(Request.QueryString["busRouteCode"]))
if (string.IsNullOrWhiteSpace(Request.Cookies["busRouteCode"]))
return View("index", "snBusRoutes");
更新: 在这种情况下,从语义上讲,执行重定向可能比 return 视图更好。用户正在提出特定请求,但该请求会将他们定向到其他地方。他们应该知道他们要去别的地方。像这样:
if (string.IsNullOrWhiteSpace(Request.QueryString["busRouteCode"]))
if (string.IsNullOrWhiteSpace(Request.Cookies["busRouteCode"]))
return RedirectToAction("index", "controllerName");
在我的项目中,我有两个控制器用于公交服务,公交路线和公交路线停靠站。为了访问路线站点,您需要 select 一条公交路线,如果一条路线尚未 selected,我需要重定向回公交路线索引。我做了一个 If else 语句来检查查询字符串和保存信息的 cookie。
当我直接去巴士路线站控制器时,它应该让我回到巴士路线列表,但它没有。
public ActionResult Index()
{
string busRouteCode = "";
//checks query string to see if empty
if (Request.QueryString == null)
{
//checks the cookies to see if empty
if (Request.Cookies["busRouteCode"] == null)
{
//if empty returns to bus route controller.
return View("index", "snBusRoutes");
}
else
{
busRouteCode = Response.Cookies["busRouteCode"].Value;
}
}
else
{
busRouteCode = Request.QueryString["busRouteCode"];
}
var routeStops = db.routeStops.Include(r => r.busRoute).Include(r => r.busStop);
return View(routeStops.ToList());
}
我不认为 Request.QueryString
完全 会成为 null。尽管特定的 value 可能为 null 或空。像这样:
if (string.IsNullOrWhiteSpace(Request.QueryString["busRouteCode"]))
if (string.IsNullOrWhiteSpace(Request.Cookies["busRouteCode"]))
return View("index", "snBusRoutes");
更新: 在这种情况下,从语义上讲,执行重定向可能比 return 视图更好。用户正在提出特定请求,但该请求会将他们定向到其他地方。他们应该知道他们要去别的地方。像这样:
if (string.IsNullOrWhiteSpace(Request.QueryString["busRouteCode"]))
if (string.IsNullOrWhiteSpace(Request.Cookies["busRouteCode"]))
return RedirectToAction("index", "controllerName");