Web API路由自定义方法



我有以下控制器:

public class CustomerController : ApiController
{
    private ICustomerService customerService;
    public CustomerController(ICustomerService customerService)
    {
        this.customerService= customerService;
    }
    public IEnumerable<Customer> GetAll()
    {
        return customerService.GetAll();
    }
    [HttpGet]
    public Customer GetCustomer(int id)
    {
        //Get customer code...
        return customer;
    }
    [ActionName("Save")]
    [AcceptVerbs("PUT")]
    [HttpPost]
    public int SaveCustomer(Customer customer)
    {
        //Save customer code...
        return customer.id;
    }
    [ActionName("Test")]
    [HttpGet]
    public string TestCustomer()
    {
        return "test";
    }
    [HttpDelete]
    public bool DeleteCustomer(int id)
    {
        //Delete customer code...
        return false;
    }
}

我有以下默认的RouteConfig:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

以及以下默认WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.EnableSystemDiagnosticsTracing();
    }
}

当我尝试~api/Customer时,我会得到以下错误:找到多个与请求匹配的操作:类型MyApp.API.Controllers.PriceLevelController上的System.Collections.Generic.IEnumerable'1[Customer]GetAll()类型MyApp.API.Controllers.CustomerController 上的System.String TestCustomer()

我需要对我的路由配置进行哪些更改,以便在从客户端调用时,我的默认方法和自定义方法都能正常工作?

我认为当您的控制器中有多个具有相同参数的get方法时,就会出现此错误。您必须在配置文件中写入另一个Routes。

您可以参考此链接

最新更新