2

I have set up a basic MVC web API project with the following method in the ValuesController class -

// GET api/values/5
public string Get(int id)
{
    return "Success!";
}

And calling this in the client like -

client.BaseAddress = new Uri("http://localhost:12345/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

 HttpResponseMessage response = await client.GetAsync("api/values/5");
 if (response.IsSuccessStatusCode)
 {
     result = await response.Content.ReadAsStringAsync();
 }

I am relatively new t MVC however I am trying to modify this method to accept string variable to be used in a database call. For instance something like -

// GET api/values/number/house/street
public string Get(string no, string house, string street)
{
    // use variables
    return "Success!";
}

Then the client something like -

HttpResponseMessage response = await client.GetAsync("api/values/" + no + house + street);
 if (response.IsSuccessStatusCode)
 {
     result = await response.Content.ReadAsStringAsync();
 }

I am essentially trying to use the API as a webservice however unsure how to modify it to work in such a way.

When I tried the above code it returned Bad Request.

0

1 Answer 1

1

You probably haven't setup the routing to your WebApi service. Check out this resource on how to set it up: http://www.asp.net/web-api/overview/web-api-routing-and-actions

EDIT:
Or, wait! If may be that the call to your service is wrong. If you look at your api method definition the comment tells you that the url should be as follows:

GET api/values/number/house/street

While it looks like you call it as:

GET api/values/NoHouseStreet

So there is no slash between the values. I am guessing that if you change the url you call to the following then things should work properly:

HttpResponseMessage response = await client.GetAsync("api/values/" + no + "/" + house + "/" + street);
Sign up to request clarification or add additional context in comments.

3 Comments

I think you are correct with your first assumption, as I have tried the second and it failed :(, I will try your first solution and will mark as correct if I get it working thank you for input.
Glad it worked. But just for the sake of completeness. Was the problem the missing slashes or routing or both?
It was the routing bud, and also my lack of understating of MVC. I had to create a custom model and controller also and now I am able to request and send data perfectly. I now realise why asmx web services should be considered deprecated. MVC is great stuff.

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.