发现了多个动作

时间:2015-05-06 12:25:04

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

  

{"消息":"发生了错误。"," ExceptionMessage":"多个   找到与请求匹配的操作:\ r \ n类型的捕获者   choreManagerWEBAPIproject.Controllers.peopleController \ r \ nPostRegister   在类型上   choreManagerWEBAPIproject.Controllers.peopleController"" ExceptionType":" System.InvalidOperationException""堆栈跟踪":"   在   System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext   controllerContext)\ r \ n at   System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext   controllerContext)\ r \ n at   System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext   controllerContext,CancellationToken cancellationToken)\ r \ n at   System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"}

以上错误让我相信我的RouteConfig不正确。

现在我在本地拨打以下电话:

$.ajax({
    url: "http://localhost:17438/api/people/PostRegister/",
    type: "POST",
    data: JSON.stringify({ name: 'Jeff', email: 'jv@test.com', phone: '5551212', carrierName: 'SPRINT'}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (result) {
        alert(result);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Status: " + textStatus); alert("Error: " + errorThrown);
    }
});

当调用此错误时,将显示错误:内部服务器错误

你可以看到我正在调用PostRegister。

    [ResponseType(typeof(string))]
    [HttpPost]
    [HttpOptions]
    public string PostRegister([FromBody] newUserRegistration newReg)
    {
        ...

        var json = JsonConvert.SerializeObject(parent.familyID);
        return json;
    }

我的RouteConfig:

        routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
        routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
        routes.MapHttpRoute("DefaultApiWithActionAndId", "Api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
        routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint("Get") });
        routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint("Post") });

我认为它应该转到这个配置:

  

DefaultApiWithAction

当我调试到WebAPI控制器时,它转到people控制器中的这一行:

public class peopleController : ApiController
{
private FamilyChoreManagerEntities db = new FamilyChoreManagerEntities();
...
}

然后我收到错误消息。然后它停止调试。

我有两种POST方法:

public void Postperson(person person)
public string PostRegister([FromBody] newUserRegistration newReg)

1 个答案:

答案 0 :(得分:0)

我认为您的请求网址错误。 Web API 2将尝试使用某些约定来匹配您的控制器方法。默认情况下,它会查找与控制器方法名称的开头不区分大小写的匹配项。在这种情况下,它通过使用Post *方法名称来识别POST方法。但是,我认为它无法找到匹配的路由,因此列出了它可以找到的两个可用的POST方法。如果您的控制器方法是PostPostRegister,我会相信它。但是,就命名约定而言,这并没有多大意义!

您应该询问Register,以便Web API可以找到PostRegister的匹配路由。即你的网址应该是

url: "http://localhost:17438/api/people/Register/"