![](/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.