Reputation: 1931
I am new to Web API. I have implemented some Web service methods [.asmx] using deprecated WebServices - with Attributes [WebMethod] and was able to place all my different methods in the .asmx file and was able to call them by the webmethod name in my ajax calls.
I am trying to move this to WebAPI, and i dont see that i could use different methods here in the WebAPI.
for ex., in my WebService.asmx file, i could declare :
[WebMethod]
public void LoadReport()
{
...
}
[WebMethod]
public void LoadReport2()
{
...
}
But in WebAPI, all i could utilize is the Get(), Put(), Post() and Delete().
How do i declare these 2 different methods in Web API ?
Upvotes: 0
Views: 1548
Reputation: 1200
Use the attribute routing in web api.
for example:
[RoutePrefix("api/Data")]
public class DataController : ApiController
{
[Route("LoadReport")]
[HttpGet]
public HttpResponseMessage LoadReport()
{
...
}
[Route("LoadReport2")]
[HttpGet]
public HttpResponseMessage LoadReport2()
{
...
}
you can access these methods by calling
http://localhost:<port>/api/sample/LoadReport
http://localhost:<port>/api/sample/LoadReport2
if you use .Net 4.5.2, ensure that the Attribute Routing is enabled.
Add the below line under Register
method of App_Start\WebAPiConfig.cs file:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes(); //enable Attribute routing
Upvotes: 3
Reputation: 1931
In WebApiConfig.cs :
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
and in my Controller :
namespace WebAPIa.Controllers
{
// [Route("api/[controller]")]
public class DataController : ApiController
{
[ActionName("LoadReport")]
[HttpGet]
public HttpResponseMessage LoadReport()
{
return Request.CreateResponse("Testing LoadReport");
}
[ActionName("LoadReport2")]
[HttpGet]
public HttpResponseMessage LoadReport2()
{
return Request.CreateResponse("Testing LoadReport2");
}
}
}
Upvotes: 1