I need to develop a web application that should respond to URL's like "api/ping.v1" (the URL's are specified externally, no option to change them) and I'm having problems, because the HttpControllerSelector is not finding my controller class. I always get the result 'Not found'. I don't know, how to configure routing, so that my controller class can be found correctly. Here is some code, what I have done so far:
Controller class:
namespace WebApplication1.Controllers
{
public class PingController : ApiController
{
[HttpPost, Route("api/ping.v1")]
public PingResponse HandleRequest(PingRequest request)
{
// TODO: Handle request and create Response object.
return new PingResponse();
}
}
}
WebApiConfig.cs:
namespace WebApplication1
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web-API-Konfiguration und -Dienste
// Web-API-Routen
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
PingRequest.cs:
namespace WebApplication1.Models
{
public class PingRequest
{
[StringLength(20)]
public string UserDms { get; set; }
[Required, StringLength(7)]
public string Ipn { get; set; }
[Required, StringLength(8)]
public string DealerId { get; set; }
[Required, StringLength(20)]
public string WorkshopPartshopId { get; set; }
}
}
Class PingResponse is completely empty, so I don't post this class here.
My HTML page for testing the web application:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ping Test</title>
</head>
<body>
<div>
<h2>Ping</h2>
<input type="button" value="Ping" onclick="ping();" />
<p id="pingResult"/>
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
function ping() {
$.post('api/ping.v1', {userDms: "wb", ipn: "Ipn", dealerId: "dealer", workshopPartshopId: "wshop"})
.done(function (data) {
$('#pingResult').text(JSON.stringify(data.response)).css("color", "black");
})
.fail(function (jqXHR, textStatus, err) {
$('#pingResult').text('Error: ' + err);
});
}
</script>
</body>
</html>
When I start my web application from Visual Studio I can see my testing site in the browser with the button "Ping". After clicking on the button ping I will get the message "Error: Not found".
I hope someone can point me to the correct direction what I am making wrong with my routing configuration.
Best Regards Michael