【问题标题】:Multiple Methods in one Controler in ASP.Net WebAPI [closed]ASP.Net WebAPI中一个控制器中的多种方法[关闭]
【发布时间】:2018-05-20 06:13:30
【问题描述】:

这是 StackOverflow 上的第一篇文章。我是 WebAPI 新手。

我在 ASP.Net 中的 WebService 已经在运行和运行。我们公司希望将 Web 服务转换为 ASP.Net WebAPI。我有一个简单的几个随机函数类,它接受多个参数并返回字符串、布尔值或小数。请记住,所有 15 种方法都没有关系,就像你可以说类名是“GeneralKnowledge” 这里有几个函数

1. public string GetPresidentName(DateTime OnTheDate,string CountryName)
2. public DateTime GetReleaseDateOfMovie(string MovieName)
3. public void AddNewCityNames(string[] CityNames)

它们都是Web Service中的WebMethod。我想创建 WebAPI,我将从 C#.Net WinForm 应用程序调用它们或与其他人共享此 API 以收集更多数据并共享更多数据

主要问题是我是否应该在一个控制器下为每个方法或动作创建单独的控制器。

当有人在一个控制器下创建多个方法时,您能否分享任何示例代码。

谢谢你 伊什拉尔。

【问题讨论】:

  • 您实际上没有问过问题。由于您是新手,因此我建议您先阅读此页面 stackoverflow.com/help/how-to-ask 此外,您确实可以在 WEB API 的一个控制器中拥有多种方法,您不必为每个方法创建单独的 Controller。跨度>

标签: c# asp.net asp.net-mvc asp.net-web-api model-view-controller


【解决方案1】:

您可以在控制器中拥有任意数量的操作。 只需使用属性路由 attribute-routing-in-web-api-2

我不建议将 15 个动作添加到一个控制器中。您可以将它们聚合成几个控制器(如 PresidentController、MovieController、RegionController)。如果您的操作彼此没有任何共同点,那么您可以创建许多不同的控制器。一个动作的 15 个控制器比一个 15 个动作的控制器更易于维护和阅读。 但最好的选择是创建几个控制器,每个控制器都只有很少的动作。

样品控制器:

[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 }
        );
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-15
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多