Web API Route 404:"在控制器上找不到匹配"

时间:2015-07-19 19:42:03

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

我一直拿到404,看不出原因?

global.asax中:

protected void Application_Start(object sender, EventArgs e)
{
    // GetApi - Allows for:
    // - GET: With or without an Id (because id is marked as 'optional' in defaults)
    RouteTable.Routes.MapHttpRoute(name: "GetApi",
                               routeTemplate: "api/{controller}/{id}",
                               defaults: new { id = RouteParameter.Optional });

    // ActionsApi - Allows for:
    // - CREATE
    // - DELETE
    // - SAVE
    // - UPDATE
    // - LIST
    // - FIND
    // - and many, many more
    RouteTable.Routes.MapHttpRoute(name: "ActionsApi",
                       routeTemplate: "api/{controller}/actions/{action}",
                       defaults: new { });

    // QueryByNameApi - Allows for:
    // - FIND: By-Name (within the URL...not the data)
    RouteTable.Routes.MapHttpRoute(name: "QueryByNameApi",
                                   routeTemplate: "api/{controller}/actions/by-name/{value}",
                                   defaults: new
                                   {
                                       value = "",
                                       action = "QueryByName"
                                   });
}

控制器:

public class SearchController : ApiController
{
    internal const string MSG_UNMANAGEDEXCEPTION = "An unexpected error occurred. Please try again.";

    // THIS WORKS !!!
    [HttpGet]
    public HttpResponseMessage Hello()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Hello back!");
    }

    // BUT...THIS FAILS ???
    [HttpPost]
    public HttpResponseMessage Find(string value)
    {
        var result = new SearchResult();

        try
        {
            var term = value.ToLowerInvariant().Trim();
            var query = Mock.Categories();

            // WHERE
            query = query.Where(x => x.Name.ToLowerInvariant().Trim().Contains(term)
                                  || x.categoryType.Name.ToLowerInvariant().Trim().Contains(term));

            // ORDER BY
            query = query.OrderBy(x => x.Name)
                         .ThenBy(x => x.categoryType.Name);

            // MATERIALIZED
            var collection = query.ToList();

            result.Filters = collection.Select(x => x.categoryType).ToList();
            result.Records = collection;
        }
        catch (Exception ex)
        {
            HttpError error = new HttpError(MSG_UNMANAGEDEXCEPTION);
            return Request.CreateResponse(HttpStatusCode.InternalServerError, error);
        }

        return Request.CreateResponse(HttpStatusCode.OK, result);
    }
}

JAVASCRIPT:
POST失败了......

$.ajax({
    type: 'POST',
    data: { "value": text },
    url: 'api/search/actions/find',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
})

但是GET成功了吗?...

$.ajax({
    type: 'GET',
    data: {},
    url: 'api/search/actions/hello',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
});

2 个答案:

答案 0 :(得分:0)

尝试将by-name routeTemplate中的QueryByNameApi替换为{action},将SearchController添加[Route("api/search/actions/find/{value:string}")]属性替换为Find()方法

编辑:

如果你想匹配ActionsApi,请尝试执行此ajax调用:

$.ajax({
    type: 'POST',
    data: { value: text },
    url: 'api/search/actions/find',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
})

否则,如果您想匹配QueryByNameApi,请尝试:

$.ajax({
    type: 'POST',
    url: 'api/search/actions/find/' + value,
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
})

答案 1 :(得分:0)

您似乎在帖子中发送了json数据,但是您已将内容类型设置为application/x-www-form-urlencoded。 我会定义一个新类来保存您的帖子值并重新定义您的帖子操作。

public class PostData
{
    public string value { get; set; }
}

控制器操作:

[HttpPost]
public HttpResponseMessage Find(PostData Data)
{
    string term = Data.value;

    //... implementation excluded
}

然后更改你的ajax电话。

$.ajax({
    type: 'POST',
    data: { "value": text },
    url: 'api/search/actions/find',
    contentType: 'application/json'
})