404在C#WebApi上找不到

时间:2015-09-29 08:06:40

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

我有一个继承自short[][][]的类,它的一些方法被正确调用,其他一些方法是ApiController。我无法找出原因。我现在一直在寻找解决方案几个小时,仍然没有得到它。请注意,我是新手,它是我在C#中的第一个WebApi。

路由:(WebApiConfig.cs)

Not found

控制器:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Configuration et services API Web

            // Itinéraires de l'API Web
            config.MapHttpAttributeRoutes();

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

JS:

public class ExchangeController : ApiController
{
    public HttpResponseMessage GetMailHeader(int id)
    {
        Console.WriteLine(id);
        HttpResponseMessage response = new HttpResponseMessage();

        response.Content = new StringContent("ok");

        return response;
    }

    public HttpResponseMessage GetTest()
    {
        HttpResponseMessage response = new HttpResponseMessage();

        response.Content = new StringContent("working !!");

        return response;
    }
}

$.ajax({ type: "GET", url: "/api/exchange/getTest", done: function (data) { console.log(data); } }); $.ajax({ type: "GET", url: "/api/exchange/getMailHeader", data: "42", done: function (data) { console.log(data); } }); 方法返回getTest200 OK返回getMailHeader。我错过了什么?

3 个答案:

答案 0 :(得分:3)

据我了解,数据添加了一个查询字符串,而不是网址本身的一部分。您将id定义为url的一部分,因此右侧URL为/ api / exchange / getmailheader / 42。 您还可以将id移出routeTemplate。

答案 1 :(得分:0)

因为您的方法以“获取”开头,并且没有特定属性,所以框架假设其为HttpGet(请参阅下面的规则2),这要求id成为url(基于默认路由)。

如果您希望它是HttpPost(您在身体中传递json对象,就像现在一样),那么在方法上方添加[HttpPost]属性或删除“获取”动作名称的一部分

Reference

  

HTTP方法。框架只选择与之匹配的动作   请求的HTTP方法,确定如下:

     
      
  1. 您可以使用以下属性指定HTTP方法:AcceptVerbs,   HttpDelete,HttpGet,HttpHead,HttpOptions,HttpPatch,HttpPost,或者   HttpPut。
  2.   
  3. 否则,如果控制器方法的名称以“Get”,“Post”,“Put”,“Delete”,“Head”,“Options”或“Patch”开头,则   按照惯例,该操作支持该HTTP方法。
  4.   
  5. 如果以上都不是,则该方法支持POST。
  6.   

答案 2 :(得分:0)

感谢大家的意见和答案,这让我找到了解决方案。

我很想写我的ajax请求。我没有从console.log在控制台上获得任何打印数据,正如@Ahmedilyas所说,data属性写得不好。

以下作品:

$.ajax({
    type: "GET",
    url: "/api/exchange/getTest"
})
.done(function (data) {
    console.log(data);
});

$.ajax({
    type: "GET",
    url: "/api/exchange/getMailHeader",
    data: { id: 42 }
})
.done(function (data) {
    console.log(data);
});