c# - ASP.Net MVC 4 API 自定义方法名称

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

我有一个问题,我想用自定义名称调用 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调用方法

我收到消息了

No action was found on the controller 'MissingCardBoxModel' that matches the request.

为什么我不能调用该方法?

最佳答案

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

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

您应该将 parcelLabelNumber 更改为 id。

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

关于c# - ASP.Net MVC 4 API 自定义方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35010010/

相关文章:

ios - 如何在 swift 2.0 或更高版本中使用 SignalR?

c# - 将特殊字符转换为普通字符

c# - 为什么 mdf 文件没有出现在 App_Data 文件夹中?

c# - SQL Server备份与恢复

c# - ASP.net MVC RC2 - 具有显式值的复选框

c# - 在异步任务完成之前返回

c# - jQgrid 搜索选项未按预期工作

c# - MAUI : await Shell. Current.GoToAsync 花费太多时间

C# winforms : graphics. DrawImage 问题

c# - 突出显示方法定义