Reputation: 1262
My apologies if the question seems trivial but being new to WebAPI i cannot
get the client access Put Methods.
Here is my WebAPI Method
public class TestController : ApiController
{
[HttpPut]
public HttpResponseMessage Put(string id)
{
var response = new HttpResponseMessage();
response.Headers.Add("Message","Success");
return response;
}
}
Route Configuration
//configure the webapi so that it can self host
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{Controller}/{action}/{id}",
defaults: new {id = RouteParameter.Optional }
);
Client
var baseAddress="http://localhost:8000/";
var client= new HttpClient {BaseAddress = new Uri(baseAddress)};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PutAsJsonAsync(baseAddress+"Test", "TestParam").Result;
Console.WriteLine(response.Content);
When i run the above code. I get 404 Error for some reason meaning the client cannot contact the webapi method.
I have three questions.
1. How can i make sure the client can correctly call the web api method.
2. Is it possible to invoke the method directly from url?
I tried http://localhost:8000/test/Dummy but no luck.
3. If its possible to invoke the method how can i make sure the message gets displayed on the page saying "Success".
Upvotes: 1
Views: 1065
Reputation: 39014
Your code would work if you didn't specify the action in the configured route. In that case the action is selected by the HTTP method (PUT, POST, DELETE, GET...). The route shpukd look like this:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
As you've specified the {action}
part in the route, you must specify the action in the url. In that case, the url should be like this:
http://localhost:8000/Test/Put
Please, see Routing in ASP.NET Web API.
If you want to test your Web API methods one of the best tools available is Postman, which is a Chrome extenion. This solves your questions 1 & 2.
For Q3: as you're making an asycn call, you have to await
for the response message, read it, and show the corresponding message. You can read this documentation if you don't know the async/await model.
Upvotes: 1