0

I am working with Attribute Routing and find it excellent. In particular the fact I can localize my routes in a number of different cultures.

I have run in to a problem that is occurring irregularly - it occurs sometimes and not others and I can not find a pattern.

The action method I have is:

 [GET("/")]
    [GET("{productId:int}")]
    [GET("{category2Id:int},{productId:int}/{category2Slug}/{productSlug}")]
    [GET("{category2Id:int},{category3Id:int},{productId:int}/{category2Slug}/{category3Slug}/{productSlug}")]
    [GET("{category2Id:int},{category3Id:int},{category4Id:int},{productId:int}/{category2Slug}/{category3Slug}/{category4Slug}/{productSlug}")]
    public virtual ActionResult Index(int productId, string productSlug = null, string category2Slug = null, string category3Slug = null, string category4Slug = null, int? category2Id = null, int? category4Id = null, int? category4Id= null)

and my controller has the following decorated on it

[SessionState(SessionStateBehavior.Disabled)]
[RoutePrefix("product", TranslationKey = "product")]
public partial class ProductController

And the issue is that sometimes attribute rendering generate the correct url eg. https://localhost/product/22,33,999/cat2/cat3/product-name but mostly it generates: https://localhost/product/999/?productSlug=product-name&category2Slug=cat2&category3Slug=cat3&category2Id=22&category3Id=33

Any idea why this is occuring and that the controller action params are being added as query string params and not part of the url?

I am working on and mvc4 application developed in C# with the version of Attribute Routing being 3.4.2.0.

Any ideas?

Charles
  • 50,943
  • 13
  • 104
  • 142
amateur
  • 43,371
  • 65
  • 192
  • 320

1 Answers1

0

You need to order your routes correctly. As you have it, there is no guarantee which of the 5 routes comes first. You can confirm by visiting routes.axd.

What happens to bugger up your urls is that the route "{productId}" is matched first, so all your route params are added as querystring values. To fix this, do a la:

[GET("product/{a}/{b}/{c}/{d}", ActionPrecedence = 1)]
[GET("product/{a}/{b}/{c}", ActionPrecedence = 2)]
[GET("product/{a}/{b}", ActionPrecedence = 3)]
[GET("product/{a}", ActionPrecedence = 4)]
[GET("product", ActionPrecedence = 5)]

This helps URL generation by ordering the routes from most specific to least. If you supply a, b, c, and d, the the first route will be used for URL gen. If only a,b, and c, the second will be used, etc....

spot
  • 2,413
  • 2
  • 19
  • 16