简体   繁体   English

Web API路线404:“在匹配的控制器上未找到任何动作”

[英]Web API Route 404: “No action was found on the controller that matches”

I keep getting a 404 and cannot see why? 我不断收到404,看不到为什么?

GLOBAL.ASAX: 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"
                                   });
}

CONTROLLER: 控制器:

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: JAVASCRIPT:
The POST fails... POST失败...

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

But the GET succeeds?... 但是GET成功了吗?

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

Try replacing by-name in the routeTemplate of QueryByNameApi with {action} and in SearchController add [Route("api/search/actions/find/{value:string}")] attribute to the Find() method 尝试用{action}替换routeTemplateQueryByNameApi by-name ,然后在SearchController中将[Route("api/search/actions/find/{value:string}")]属性添加到Find()方法

Edit: 编辑:

If you want to match ActionsApi try executing this ajax call: 如果要匹配ActionsApi尝试执行以下ajax调用:

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

else if you want to match QueryByNameApi try: 否则,如果要匹配QueryByNameApi尝试:

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

You appear to be sending json data in your post however you have set your content type to application/x-www-form-urlencoded . 您似乎在帖子中发送json数据,但是将内容类型设置为application/x-www-form-urlencoded I would define a new class to hold your post values and redefine your post action. 我将定义一个新类来保存您的帖子值并重新定义您的帖子操作。

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

Controller Action: 控制器动作:

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

    //... implementation excluded
}

Then change your ajax call. 然后更改您的ajax调用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 找不到Web API路由404 - 404 Not Found for Web API Route Rails 4:找不到对控制器操作的ajax调用,返回404 - Rails 4: ajax call to controller action returning 404 not found 未找到注册路由 404 - Register route 404 not found ActionView :: Template :: Error(没有路由与{:action =>“ show”,:controller =>“ administration / roles”……可能不匹配的约束:[:id]): - ActionView::Template::Error (No route matches {:action=>“show”, :controller=>“administration/roles” … possible unmatched constraints: [:id]): 未找到 Web API POST(在浏览器上抛出 404)但适用于 PostMan 和 Swagger - Web API POST not found (throws 404 on browser) but works on PostMan and Swagger 找不到Bing Web Search API GET请求返回404 - Bing Web Search API GET request returning 404 not found 找不到XML字符串传递到Web API结果404 - Passing XML String to Web API Results in 404 Not Found 在MVC 5应用中的api Web API 2控制器中无法执行操作 - Cannot reach Action in api Web API 2 Controller in MVC 5 app 如何在 NextJS 中使用 next/link 调用链接 api 路由时修复 net::ERR_ABORTED 404(未找到) - How to fix net::ERR_ABORTED 404 (Not Found) when callink api route using next/link in NextJS Angular Controller在路线参数上返回404 - Angular Controller returns 404 on a Route Parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM