1

Looking at the help Attribute Routing in ASP.NET MVC 5 it is easy to see how to constraint a parameter as below:

[Route("edit/{promoId:int?}")]
public ActionResult Edit(int? promoId) { … } 

So this route will only accept promoId with int values or empty.

Some valid URLs for this route would be:

/promotions/edit/5
/promotions/edit/

But how to set a RouteAttribute to accept "/promotions/edit/promoId=5"?

2 Answers 2

2

You try to set it in RouteConfig.cs in your App_Start folder by pointing that kind of URL to your action.

routes.MapRoute(
           name: "Edit",
           url: "{controller}/{action}/promoId={promoId}",
           defaults: new { controller = "Promotions", action = "Edit", promoId = UrlParameter.Optional }
);
Sign up to request clarification or add additional context in comments.

5 Comments

The problem with this is that if you have promoId as Int type, you receive an error if the url is trying to pass a string. I'm trying to avoid this error for google crawler.
It will not be routed to this URL since it needs to have an integer. try to test this using PostMan or Telerik Fiddler
It works! The only thing different from you comment is that the controller action is called when the parameter type is different, but no value is passed to it, since it is int? The test is here: github.com/mqueirozcorreia/AspnetMVCRouteTest
@mqueirozcorreia: be advised; although this is a nice way to get your result, the url format is not really common. Usually the ? querystring marker is used or parameters are sepperated in a www.example.org/something/promoId/someotherIdperhaps/ like format
@mqueirozcorreia well, at least you are getting the correct route. It is up to the consumer/user of your API to parse the result. Happy to help, good luck to your project.
2

Actually, I think the url should be in this format:

/promotions/edit?promoId=5

Note the ?. It's the beginning of the query string marker.

It should be possible to do it this way:

[Route("edit")]
public ActionResult Edit([FromUri]int promoId)
{
    ...
}

5 Comments

why promoId is not int?
I can see you idea to convert promoId from string to int. I think it works, but should not be better to use constraint? I have tried using two routes, as below: [Route("edit/promoId={promoId:int?}")] [Route("edit/{promoId:int?}")] I can use promoId as integer and optional. What do you think?
@Coding: sorry, my typo bad
@mqueirozcorreia: sorry, I meant int; It was late in the evening for me ;-)
Asp.net MVC has a equivalent to [FromUri] as the answer below: stackoverflow.com/a/28769621/3424212 But we get error when the promoId is not an error. The test is here: github.com/mqueirozcorreia/AspnetMVCRouteTest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.