在c# WebApi上找不到404

本文关键字:找不到 WebApi | 更新日期: 2023-09-27 18:15:15

我有一个继承自ApiController的类,它的一些方法被正确调用,其他一些是Not found。我不知道为什么。我已经找了好几个小时的解决办法了,还是没找到。注意,我是新手,这是我在c#中的第一个WebApi。

路由(WebApiConfig.cs):

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 }
            );
        }
    }

控制器:

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;
    }
}

JS:

$.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);
    }
});

getTest方法返回200 OK,而getMailHeader返回404 Not Found。我错过了什么?

在c# WebApi上找不到404

据我所知,data添加了一个查询字符串,而不是url本身的一部分。您将id定义为url的一部分,因此正确的url是/api/exchange/getmailheader/42。你也可以把id从routeTemplate中移出。

因为你的方法以'Get'开头,并且没有特定的属性,框架假设它是一个HttpGet(见下面的规则2),这需要id是url的一部分(基于默认路由)。

如果你想要它是一个HttpPost(你在身体传递json对象,就像你现在做的),然后在你的方法上面添加一个[HttpPost]属性或删除动作名称的"Get"部分

参考

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

  1. 你可以用一个属性来指定HTTP方法:AcceptVerbs,HttpDelete, HttpGet, HttpHead, httppoptions, httpppatch, HttpPost,或HttpPut。
  2. 如果控制器方法名称以"Get"、"Post"、"Put"、"Delete"、"Head"、"Options"或"Patch"开头,则按照约定,该操作支持该HTTP方法。
  3. 如果以上都不是,该方法支持POST。

感谢大家的意见和回答,它使我找到了解决方案。

我错过了写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);
});