简体   繁体   中英

Remove controller name from URL with Attribute routing

I want to remove controller name from URL for specific Controller.

My Controller name is Product

I found some link to do this

Routing with and without controller name

MVC Routing without controller

But all the above links done in route config file. and those are affecting other controller too. I want to do it using Attribute Routing.

Can it is possible? As I want to do this for only Product controller.

I have tried to do it on action like this

[Route("Sample/{Name}")]

but it is not working.

Gabriel's answer is right, however, it can be a bit misleading since you're asking for MVC and that answer is for Web API.

In any case, what you want is to put the annotation over the class definition instead of an action method. MVC example would be like:

[RoutePrefix("SomethingOtherThanProduct")]
public class ProductController : Controller
{
      public ActionResult Index()
      {
           ...
           return View();
      }
}

I'm also dropping this as an answer since you may find the following article helpful: [Attribute] Routing in ASP.NET MVC 5 / WebAPI 2

Make sure you set the RoutePrefix attribute on the whole controller class, as well as using the Route attribute on the action.

[RoutePrefix("notproducts")]
public class ProductsController : ApiController
{
    [Route("")]
    public IEnumerable<Product> Get() { ... }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM