Multiple Methods in one Controler in ASP.Net WebAPI
This is first post on StackOverflow. I am new to WebAPI.
I have WebService in ASP.Net already running and functioning. Our company wants to convert Web Service in to a ASP.Net WebAPI. I have a simple class of few random functions which takes multiple parameters and returns string or bool or decimals. Remember that all 15 methods do not have relation with each other like you can Say Class Name is "GeneralKnowledge" here are few Functions
1. public string GetPresidentName(DateTime OnTheDate,string CountryName)
2. public DateTime GetReleaseDateOfMovie(string MovieName)
3. public void AddNewCityNames(string[] CityNames)
All of them are WebMethod in Web Service. I want to create WebAPI and I will call them from C#.Net WinForm app or Share this API with other people to collect more data and share more data
The main question is that should I create individual Controller for each method or actions under one controller.
Can you please share any example code when anyone has created multiple methods under one controller.
Thanking you Ishrar.
You can have as many actions in controller as you want. Just use attribute routing attribute-routing-in-web-api-2
I don't recommend adding 15 actions into one controller. You can agregate them into few controllers (like PresidentController, MovieController, RegionController). If Your actions dosn't have anything in common with each other then You can create many different controllers. 15 controllers with one action is easier to maintain and read then one controller with 15 actions. But best option is to create few controllers with few actions in each.
Sample controller:
[RoutePrefix("api/presidents")]
public class PresidentsController : ApiController
{
[Route("GetFirstPresident/{countryName}")]
public IHttpActionResult GetFirstPresident(string countryName)
{
var president = string.Format("First president of {0} was XYZ", countryName);
return Ok(president);
}
[Route("GetPresident/{number}/{countryName}")]
public IHttpActionResult GetPresident(int number, string countryName)
{
var president = string.Format("{1} president of {0} was XYZ", countryName, number);
return Ok(president);
}
}
WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
链接地址: http://www.djcxy.com/p/62580.html
上一篇: 用于查询的定义的搜索项