[英]Easiest way to do URL rewrite in .NET
I have a blog that I have built. 我有一个自己建立的博客。 It uses a web api in c# .NET.
它使用c#.NET中的Web API。
If you click here: http://www.judsondesigns.com/api/blogapi/17 如果您单击此处: http : //www.judsondesigns.com/api/blogapi/17
You will see it return an entry from the server. 您将看到它从服务器返回一个条目。 How can I easily rewrite the url to use the blog title instead of the ID?
如何轻松重写网址以使用博客标题而不是ID?
So instead you can access it via: http://www.judsondesigns.com/api/blogapi/my_blog_tite_here 因此,您可以通过以下网址访问它: http : //www.judsondesigns.com/api/blogapi/my_blog_tite_here
I have done this with isapi rewrites in the past on linux, but wasnt clear how to in .NET. 我过去在Linux上使用过isapi重写来做到这一点,但并不清楚如何在.NET中进行。 I have heard different way but would like the less is more approach here.
我听到了不同的方法,但希望这里的方法越少越好。 Thanks in advance.
提前致谢。 -Judson
-贾德森
What you want to do is create a custom RouteBase
. 您要做的是创建一个自定义
RouteBase
。 This code review post is a good place to start. 这段代码审查帖子是一个不错的起点。
The jist of it is: 其关键是:
public class MyRoute : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
// parse url and turn into route
}
public override VirtualPathData GetVirtualPath(
RequestContext requestContext,
RouteValueDictionary values)
{
// create url from route
}
}
Which you then register along with any other routes like 然后您将其与其他任何路线一起注册
routes.Add(new MyRoute());
By editing the route configuration: 通过编辑路由配置:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{blogTitle}",
defaults: new { controller = "Home", action = "Index", blogTitle = UrlParameter.Optional }
);
}
}
or rewrite the action to use the name instead and using a named parameter http://www.judsondesigns.com/api/blogapi/?blogtitle=my_blog_tite_here 或重写操作以改用名称,并使用命名参数http://www.judsondesigns.com/api/blogapi/?blogtitle=my_blog_tite_here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.