【问题标题】:Web Api Multiple actions were foundWeb Api 发现多个动作
【发布时间】:2015-07-31 08:39:07
【问题描述】:

我有不同类型参数的动作。

public class MyController : ApiController
{       
    [HttpPost]
    public UpdateFeatureResponse UpdateFeature(UpdateFeatureResuest reqResuest)
    {
        return new UpdateFeatureResponse { IsSuccess = true };
    }

    [HttpPost]
    public DeleteFeatureResponse DeleteFeature(DeleteFeatureRequest request)
    {
        return new DeleteFeatureResponse{ IsSuccess = true };
    }

}

而我的请求类型是这样的:

public class UpdateFeatureResuest
{
    public int Id { get; set; }
    public string Feature { get; set; }
}

public class UpdateFeatureResponse
{
    public bool IsSuccess { get; set; }
}

public class DeleteFeatureRequest
{
    public int Id { get; set; }
}

public class DeleteFeatureResponse
{
    public bool IsSuccess { get; set; }
}

路线在这里:

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

当我通过提琴手发送请求 (http://localhost:52285/api/My/UpdateFeature) 时,它返回 HTTP/1.1 500 Internal Server Error

错误信息是:

{"message":"发生错误。","exceptionMessage":"找到与请求匹配的多个操作:\r\nUpdateFeature on type WebGUI.Controllers.MyController\r\nDeleteFeature on type WebGUI.Controllers .MyController","exceptionType":"System.InvalidOperationException","stackTrace":" .....

【问题讨论】:

  • 您使用了什么 URL,您的路由是什么样的?

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


【解决方案1】:

您的路线错误,因为它没有指定操作名称,因此它将UpdateFeature 部分视为 ID 参数。改成这样:

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

【讨论】:

  • 我的路由是web api模板的默认路由。但是您的解决方案有效。谢谢
【解决方案2】:

最好使用Route属性。

例如

[RoutePrefix("myapi")]
public class MyController : ApiController
{       
    [Route("update")]
    [HttpPost]
    public UpdateFeatureResponse UpdateFeature(UpdateFeatureResuest reqResuest)
    {
        return new UpdateFeatureResponse { IsSuccess = true };
    }

    [Route("delete")]
    [HttpPost]
    public DeleteFeatureResponse DeleteFeature(DeleteFeatureRequest request)
    {
        return new DeleteFeatureResponse{ IsSuccess = true };
    }

}

现在将其添加到您的 WebApiConfig 之前的 config.Routes.MapHttpRoute()

config.MapHttpAttributeRoutes();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多