【问题标题】:Mvc customize routesMvc 自定义路由
【发布时间】:2018-05-04 07:01:26
【问题描述】:

我只想在 asp.net mvc 中自定义路由, 这是一个博客网站,我想使用

访问控制器方法

www.sitename.com/blog/{blogtitle}

www.sitename.com/blog/{action}

博客控制器

 public class BlogController : Controller
{

  public ActionResult Index(string title)
    {
        return View();
    }



        [Route("post-blog")]
    [HttpPost]
    public ActionResult Post(Blog blog,HttpPostedFileBase blogimage)
    {

        //some coe

    }
    [Route("post-blog")]
    public ActionResult Post()

    {

        if (Request.Cookies["userInfo"]==null)
        {
            return Redirect("/login");
        }

        return View();
    }

}

这里是路由配置

  public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //routes.Canonicalize().Www();
        routes.Canonicalize().Lowercase();




        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "freelogomaker", id = UrlParameter.Optional }
        );


  }

但我无法使用 www.site.com/blog/titlename 来点击操作名称“索引” 但我可以使用 www.site.com/blog/post-blog 访问“post-blog”

请帮助我,我是 asp.net mvc 路由的初学者。

【问题讨论】:

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


    【解决方案1】:

    将您的参数添加到 {} 括号内的路由属性中,以表明它应该从 URL 中读取,而不是从其他内容(例如 POST 正文、依赖注入等)中读取

    [Route("{title}")]
    public ActionResult Index(string title)
    {
        return View();
    }
    

    我还想给控制器添加RoutePrefix属性,让它更清晰一些。

    [RoutePrefix("blog")]
    public class BlogController : Controller
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多