ASP.NET MVC在action方法中删除查询字符串

时间:2012-03-12 18:38:01

标签: asp.net asp.net-mvc routing query-string

我有一个看起来像这样的动作方法:

public ActionResult Index(string message)
{
  if (message != null)
  {
    ViewBag.Message = message;
  }
  return View();
}

请求的URL将如下所示:

www.mysite.com/controller/?message=Hello%20world

但我希望它看起来只是

www.mysite.com/controller/

有没有办法删除actionmethod中的查询字符串?

5 个答案:

答案 0 :(得分:20)

不,除非您使用POST方法,否则必须以某种方式传递信息。另一种选择可能是使用中间类。

// this would work if you went to controller/SetMessage?message=hello%20world

public ActionResult SetMessage(string message)
{
  ViewBag.Message = message ?? "";
  return RedirectToAction("Index");
}

public ActionResult Index()
{
  ViewBag.Message = TempData["message"] != null ? TempData["message"] : "";
  return View();
}

或者。如果您只是使用POST

//your view:
@using(Html.BeginForm())
{
    @Html.TextBox("message")
    <input type="submit" value="submit" />
}


[HttpGet]
public ActionResult Index()
{ return View(); }

[HttpPost]
public ActionResult Index(FormCollection form)
{
  ViewBag.Message = form["message"];
  return View();
}

答案 1 :(得分:1)

我不确定你是不是真的在想。如果你删除查询字符串...然后删除查询字符串..即,你的页面将没有查询字符串值来做它需要做的任何事情。

你可以做很多不同的黑客......所有这些都不理想。您可以使用javascript去掉查询字符串。您可以在设置会话变量后重定向到无查询字符串的页面。这一切都非常难看。

请记住,用户在地址栏中看到的内容位于客户端上。客户端控制它。你可以通过javascript来摆弄它,但这样做通常是一个坏主意。由于从用户隐藏内容可被视为类似恶意软件的行为。

答案 2 :(得分:1)

查看routes。它们定义了如何写入带参数的URL。

如果您创建一个新的MVC应用程序,并查看`RegisterRoutes()下的Global.asax.cs文件。你应该看到一个条目。

routes.MapRoute(
   "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "home", action = "index", id = UrlParameter.Optional } // Parameter defaults
        );

看看每个部分:

  • &#34;默认&#34;是名字。这对于您创建的每条路线都必须是唯一的。
  • &#34; {控制器} / {行动} / {ID}&#34;是您想要使用的模式。 example.org/home/index?id=2example.org/home/index/2代替
  • new {controller =&#34; home&#34;,action =&#34; index&#34;,id = UrlParameter.Optional}定义了默认值,如果没有指定的话。

所以,如果你去 example.org 那条路线就是这样的,它会假设你的意思是 example.org/home/index {id is optional} 。< / p>

通过这种方式,您可以开始了解如何创建自己的路线。

现在,解决您的问题,简短的回答是您可以使网址看起来像那样,但不是真的。您必须使用默认消息定义路由,并且只有在某人没有指定消息时才会显示。您必须告诉控制器消息是什么。对不起,但你能做的最好的事情是定义一条给你的路线

/message/Hello%20World并使用string.replace让它看起来更漂亮`&#39; / message / hello_world&#39;

答案 3 :(得分:0)

我建议使用slu ..看看这篇文章:SOF Slug post 在以前的应用程序中,我采用这种方法从URL中删除了查询字符串。

答案 4 :(得分:0)

您可以通过在剃刀视图中添加一些JavaScript来删除查询字符串。

@section scripts{
    <script>
        if (location.href.includes('?')) { 
            history.pushState({}, null, location.href.split('?')[0]); 
        }
    </script>    
}

如果您导航到页面

www.mysite.com/controller/?message=Hello%20world

然后它将显示

www.mysite.com/controller/

在浏览器中。

大多数现代浏览器都支持(browser support)。