![](/img/trans.png)
[英]C# webapi Cors Option request in server returns error 404 not found
[英]404 Not found on C# WebApi
我有一個繼承自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
。 我錯過了什么 ?
據我了解,數據添加了一個查詢字符串,而不是url本身的一部分。 您將id定義為url的一部分,因此右側URL為/ api / exchange / getmailheader / 42。 您還可以將id移出routeTemplate。
因為您的方法以'Get'開頭,並且沒有特定屬性,所以框架假定它是一個HttpGet
(參見下面的規則2),這要求id
是url的一部分(基於默認路由)。
如果你希望它是一個HttpPost
(你在身體中傳遞一個json對象,就像你現在所做的那樣),那么在你的方法上面添加一個[HttpPost]
屬性或刪除動作名稱的'Get'部分
HTTP方法。 框架僅選擇與請求的HTTP方法匹配的操作,確定如下:
- 您可以使用以下屬性指定HTTP方法:AcceptVerbs,HttpDelete,HttpGet,HttpHead,HttpOptions,HttpPatch,HttpPost或HttpPut。
- 否則,如果控制器方法的名稱以“Get”,“Post”,“Put”,“Delete”,“Head”,“Options”或“Patch”開頭,則按照慣例,該操作支持該HTTP方法。
- 如果不是上述方法,則該方法支持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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.