Skip to main content
 首页 » 编程设计

c#之404 在 C# WebApi 上找不到

2024年05月29日45shanyou

我有一个继承自ApiController 的类,它的一些方法被正确调用,另一些方法未找到。我不知道为什么。几个小时以来,我一直在寻找解决方案,但仍然没有得到。请注意,我是新手,这是我在 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 } 
            ); 
        } 
    } 

Controller :

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。我错过了什么?

请您参考如下方法:

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