我想创建一个 URL 缩短器网站。我提供的 URL 就像短 URL 的值在example.com/XXX
哪里
。XXX
我想有网站example.com
,网址是example.com/xxx
. 我想xxx
从 URL 获取并将用户重定向到数据库中的等效 URL。
如何实现这一点?
我想创建一个 URL 缩短器网站。我提供的 URL 就像短 URL 的值在example.com/XXX
哪里
。XXX
我想有网站example.com
,网址是example.com/xxx
. 我想xxx
从 URL 获取并将用户重定向到数据库中的等效 URL。
如何实现这一点?
在 RouteConfig 中创建一个新路由,例如:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("empty",
"{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
只需使用索引中传递的 id 进入您的数据库
public ActionResult Index(int id)
{
//Do Stuff with db
return View();
}
asp.net mvc 文档在这里。
您在默认控制器操作中执行所需重定向的一种方式。默认情况下,在 asp.net mvc 中它是 home/index。
所以在索引操作中你应该有这样的代码
public ActionResult Index(string id)
{
var url = Db.GetNeededUrl(id);
return Redirect(url);
}
因此,现在如果用户输入这样的地址 site.com/NewYear,您将被重定向到数据库中的等效 url。