这与 IIS URL 重写无关。它是关于 ASP.NET 路由的。
看起来肯定会忽略问题 ID 之后的字符串。因为它在没有这个字符串参数的情况下也能工作,所以它可能是为了方便用户使用。
在 ASP.NET MVC 中有路由。如果您对此不太了解,请阅读这两篇文章:at MSDN、at ASP.NET。
默认情况下,您有以下RouteConfig:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional }
);
这意味着如果你有这样的动作:
public class InformationController : Controller
{
public ActionResult Get(int id)
{
// ...
}
}
那么你可以通过以下方式访问它:
http://yourwebsite.com/Information/Get/7325278
与
相同
http://yourwebsite.com/Information/Get/?id=7325278
如果您想要一个额外的参数,您可以更改您的路线以使用 2、3 或更多参数。
然后,你会做一个
http://yourwebsite.com/Information/Get/7325278/group-by-in-linq
相当于
http://yourwebsite.com/Information/Get/?id=7325278&someParam=group-by-in-linq
这里是StackOverflow topic about routes with multiple arguments。
假设您现在有多个参数路由。
现在,您可以在您的操作中描述任何逻辑。例如,您可以在代码中使用此参数,也可以忽略第二个参数并重定向到必要的 URL(StackOverflow 的做法)。
也许,我的伪伪代码会帮助你:
public ActionResult Get(int id, string unnecessaryString)
{
var question = questionsDbProvider.getById(id);
if (question.ShortUrlText == unnecessaryString)
return RedirectToAction("Get", new {
id = id,
unnecessaryString = question.ShortUrlText
});
}
这样的动作代码将检查它的第二个参数是否正确,否则重定向到正确的。
301 重定向正是 StackOverflow 使其以这种方式工作的方式。您可以在浏览器开发者工具的 Network 标签中查看。