【问题标题】:Can I create more function in ApiController?我可以在 ApiController 中创建更多功能吗?
【发布时间】:2013-11-09 05:55:44
【问题描述】:

我是 web api 的新手,我正在使用默认的 Web API 创建一个演示,我看到 ValuesController 具有默认的 4 个函数 Get、Post、Put 和 Delete。我看到 ValuesController 对无法修改的 ApiController 实现了 4 功能。那么,我可以写一些更多的功能,比如按价格或型号搜索项目吗?如果可以,在浏览器上运行调试新功能的 url 是什么?

谢谢

【问题讨论】:

  • 在 VS 中按 Start with Debugging 按钮,您的浏览器将启动,您可以在地址栏中看到地址。
  • 不,我不问如何运行调试,我问为 web ApiController 创建新函数,以及运行该函数的添加衣服,谢谢

标签: asp.net-mvc-4 asp.net-web-api


【解决方案1】:

听起来您需要向控制器添加新操作。您需要在 WebApiConfig.cs 文件中修改(或添加)您的路由以包含操作映射。

例如,假设您使用附加函数 GetTestString1 和 GetTestString2 更新您的控制器:

public class TestController : ApiController
{
    public String GetTestString1(int id)
    {
        return "Test String 1 for " + id;
    }

    public String GetTestString2(int id)
    {
        return "Test String 2 for " + id;
    }
}

要执行到这些新功能的路由,您需要将以下内容添加到 App_Start 文件夹中的 WebApiConfig.cs 文件中:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        // This mapping entry may already exist for you. Leave it alone 
        // so your existing default functions continue to work properly.  
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );             

        // Add this to route your new functions:  
        config.Routes.MapHttpRoute(
            name: "TestStringApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );


    }
}

上面的 routeTemplate "api/{controller}/{action}/{id}" 是请求 URL 将如何路由到您的控制器和操作(函数)的方式。 URL 的 {controller} 部分将路由到您的 TestController 类。 URL 的 {action} 部分是您询问的附加功能,将根据您在 URL 中请求的内容映射到 GetTestString1 或 GetTestString2。

当您打开浏览器访问该地址时,

http://localhost:60303/api/Test/GetTestString1/100

您在 WebApiConfig.cs 中注册的路由会将 url 映射到您的 Testcontroller 的 GetTestString1 操作(函数),并将 100 作为输入参数,并将“Test String 1 for 100”返回给浏览器。

您可以像这样调用您的 Testcontroller 的 GetTestString2 操作(函数)

http://localhost:60303/api/Test/GetTestString2/101

和“Test String 2 for 101”将返回给浏览器。

您可以在此处详细了解默认函数的工作原理(获取、删除后)以及有关操作和参数的更多信息:

以下是一些与本主题类似的相关讨论:

【讨论】:

    猜你喜欢
    • 2012-07-31
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多