【问题标题】:ASP.Net MVC 4 API custom method nameASP.Net MVC 4 API 自定义方法名称
【发布时间】:2016-01-26 08:55:15
【问题描述】:

我有一个问题,我想用自定义名称调用 MVC Api 方法。

我按照here 的描述更改了 WebApi.config

    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id="test" }
    );

写了一堂课

public class MissingCardBoxModelController : ApiController
{
    // GET api/missingcardboxmodel
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/missingcardboxmodel/5
    public string Get(string id)
    {
        return id;
    }

    public string GetTrackingNumber(string parcelLabelNumber) 
    {
        string trackingNumber = "some number";
        return trackingNumber;
    }

    // POST api/missingcardboxmodel
    public void Post([FromBody]string value)
    {
    }

    // PUT api/missingcardboxmodel/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/missingcardboxmodel/5
    public void Delete(int id)
    {
    }
}

但是我不能通过http://localhost:58528/api/MissingCardBoxModel/GetTrackingNumber/123456调用方法

我收到消息

在控制器“MissingCardBoxModel”上没有发现任何动作 匹配请求。

为什么我不能调用方法?

【问题讨论】:

  • 你用的是什么web api版本?
  • 尝试将参数中的 parcelLabelNumber 更改为 id
  • 我使用 Webapi Controller v1
  • @BrendanGreen 好的,问题解决了。我知道问题出在哪里。我以为变量名 id 只是一个占位符。

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


【解决方案1】:

如果您的路由配置为这些(MVC 解决方案模板中的默认设置):

url: "{controller}/{action}/{id}"

你应该把parcelLabelNumber改成id。

您可以阅读更多关于路线的信息here

【讨论】:

    【解决方案2】:

    默认情况下,Web API 允许使用 Restful 约定,这意味着它将自动映射 GET, PUT, POST, DELETE 等操作名称。如果您在路线中查看WebApiConfig 内部,它只允许下面的路线

    config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    

    这意味着它只允许

    .../api/yourcontrollername/a parameter that will map to id

    。 你基本上有两个选择,一个使用attribute routing。或者您可以将路由添加到您的自定义方法,例如:

    config.Routes.MapHttpRoute(
                    name: "custom",
                    routeTemplate: "api/{controller}/{action}/{parcelLabelNumber}",
                    defaults: new { parcelLabelNumber = "" }
                );
    

    请注意此处的参数名称“parcelLabelNumber”,您必须在此处将参数命名为与您的操作中相同的名称。您应该可以通过 -http://localhost:23691/api/MissingCardBoxModel/GetTrackingNumber/1245

    进行此操作

    另外请查看general中的路由

    【讨论】:

      猜你喜欢
      • 2012-03-23
      • 1970-01-01
      • 2018-09-21
      • 2015-06-22
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多