0

I have created an Action in my Home Controller which accepts a text:

 public class HomeController : Controller
    {
       public string DisplayText(string text)
        {
            return text;
        }
    }

I can call this Action, using the below url by passing the text parameter as a query string:

http://localhost:4574/Home/DisplayText?text=some text

However, I'd like to be able to call this using the below style:

http://localhost:4574/Home/DisplayText/some text

Therefore without specifying the parameter name ("text");

How would that be possible?

Another example to explain it more clearly is as below

public string Add(string a, string b)
        {
            return (int.Parse(a) + int.Parse(b)).ToString();
        }

I can call it using:

http://localhost:4574/Home/Add?a=2&b=3

but how to call it in a RESTFul way? e.g. (http://localhost:4574/Home/Add/2/3)

1 Answer 1

3

You could define a route:

routes.MapRoute(
    "MyRoute",
    "{controller}/{action}/{a}/{b}",
    new { controller = "Home", action = "Add" },
    // it's always a good idea to define route constraints
    // in this case we are constraining the a and b parameters to numbers only
    new { a = @"\d+", b = @"\d+" } 
);

and then:

public ActionResult Add(int a, int b)
{
    return Content(string.Format("The result of {0}+{1}={2}", a, b, a + b));
}
Sign up to request clarification or add additional context in comments.

8 Comments

you beat me to it :). However, he should consider when it really should be part of the url or when it should be a parameter.
@TomasJansson, yes, that's an important design choice to make.
@TomasJansson, several answers are encouraged. Your could contain the query-vs-resource tips. :)
@bzlm, that's more of a sidnote. Except from that my answer was exactly the same so I deleted it. The sidnote is here now on the answer with the most votes which make it easier to find.
thanks. couple of questions 1) why would you rather returning ActionResult rather than string? 2) putting route constraints will constraint all the routes in the application so that doesn't seem to be a good idea since some Actions may have different data types e.g. string, etc. right? so how would you write it without constraint?
|

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.