我在网上找到的东西和我在实践考试中读到的内容感到困惑.
关于SO状态的几个问题,使用RedirectToAction将浏览器发送到302,从而使其在地址栏中更改其url.
但这是一个练习测试中的一个问题:
题:
The MVC Home controller currently has only the default Index action. The relevant code is shown in the following code example.
public ActionResult Index() { ViewData["Message"] = "Hello!"; return View(); }
You need to create an action named FindID that displays the ID parameter entered as part of the path. If the path does not include an ID parameter,ASP.NET must process the Index action without changing the URL in the browser’s address bar,and must not throw an exception.
Which code segment should you use?
正确答案:
public ActionResult FindID(int? id) { if (!id.HasValue) return RedirectToAction("Index"); ViewData["Message"] = "ID is " + id.ToString(); return View(); }
说明:
You can use the RedirectToAction form of ActionResult to cause MVC to process a different action from within an action. MVC abandons the current action and processes the request as if the route had led directly to the action you redirect to. Essentially,this is equivalent to calling Server.Transfer in a standard ASP.NET application.
The Redirect ActionResult sends an “HTTP Error 302 – Found” response to the browser,which causes the browser to load the specified URL. This changes the address that appears in the address bar.
所以:
– RedirectToAction是否使浏览器中的URL保持不变?
– 重定向是否更改浏览器中的URL?
– 练习测试的解释是否正确?从那个我明白,RedirectToAction不做一个302.
解决方法
You can use the RedirectToAction form of ActionResult to cause MVC to process a different action from within an action. MVC abandons the current action and processes the request as if the route had led directly to the action you redirect to. Essentially,this is equivalent to calling Server.Transfer in a standard ASP.NET application.
这是不正确的
RedirectToRouteResult(RedirectToAction)和RedirectResult都执行302重定向,导致浏览器中的URL更改.
要返回索引结果而不更改代码实际上的url:
public ActionResult FindID(int? id) { if (!id.HasValue) return View("index"); ViewData["Message"] = "ID is " + id.ToString(); return View(); }
不过,我不会推荐这种方法.如果我要求mysite.com/products/some-product和某些产品不存在,那么我应该通过相关的状态代码通知用户(对搜索引擎也很重要).
如果您的FindID操作的唯一目的是使用id参数执行某些操作,那么它不应该是空的/可选的.这样,如果未指定ID,则不会调用FindID操作.