C# Web API 405 GET 错误
C# Web API 405 Error on GET
经过十年的桌面开发,我是 restful API 的新手。我有点困惑为什么我会收到 405 尝试 GET 控制器。
我的控制器:
public class ApplicantsController : ApiController
{
/// <summary>
/// Gets the details of the applicant and their application
/// </summary>
/// <param name="applicantID">The ID of the applicant to get the most recent application and details for</param>
/// <returns></returns>
public HttpResponseMessage Get(int applicantID)
{
try
{
using (DbQuery query = new DbQuery("SELECT * FROM Applicants AS A WHERE A.ID = @ApplicantID",
new DbParam("@ApplicantID", applicantID)))
{
using (DataTable data = query.ExecuteDataTable())
{
if (data.Rows.Count > 0)
{
Applicant applicant = new Applicant(data.Rows[0]);
return new HttpResponseMessage()
{
Content = new StringContent(applicant.ToJson(), Encoding.UTF8, "text/html")
};
}
}
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
catch (Exception ex)
{
Methods.ProcessException(ex);
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
public HttpResponseMessage Post(Applicant applicant)
{
if (applicant.Save())
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, applicant);
string uri = Url.Link("DefaultApi", new { id = applicant.ID });
response.Headers.Location = new Uri(uri);
return response;
}
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Error saving applicant");
}
}
}
我在我的 WebApiConfig 中有相同的默认路由,并确认我的控制器的编写方式与标准的 Web API 2 控制器匹配,具有读取、写入、更新方法。我试过使用 DefaultAction,我试过用 [HttpGet] 和 [AcceptVerbs] 装饰方法。每当我自己尝试通过浏览器或通过 ajax 访问 Get 时,我都会收到 405(不允许的方法)。
Ajax 测试:
$("#TestGetApplicantButton").click(function (e) {
e.preventDefault();
alert("Getting Applicant...");
$.ajax({
type: "GET",
url: "/api/Applicants/108",
contentType: "application/json; charset-utf-8",
dataType: "json",
success: function (data) {
$("#ResponseDiv").html(JSON.stringify(data));
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
Ajax 完美适用于所有其他控制器,显示返回的数据(示例:,它甚至在 this[ 上调用 Post 方法=33=] 控制器很好。但我无法开始工作。我看不出哪里出错了。
我的路线:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
我在这里进行了 google 和检查,但似乎每个人都只对 POST、PUT 或 DELETE 有问题,所以我还没有找到答案。我还尝试删除控制器中的 POST 方法 - 这让我得到了 404(不是来自我的 404,我确认代码没有执行),这表明由于某种原因路由无法找到我的 get 方法完全。
您需要为 applicantID 参数添加一个默认值,因为您的路由的第一个参数标记为 RouteParameter.Optional
。
public HttpResponseMessage Get(int applicantID = 0)
这将确保您的 Get 方法签名与您的 "DefaultApi" 路由匹配。
经过十年的桌面开发,我是 restful API 的新手。我有点困惑为什么我会收到 405 尝试 GET 控制器。
我的控制器:
public class ApplicantsController : ApiController
{
/// <summary>
/// Gets the details of the applicant and their application
/// </summary>
/// <param name="applicantID">The ID of the applicant to get the most recent application and details for</param>
/// <returns></returns>
public HttpResponseMessage Get(int applicantID)
{
try
{
using (DbQuery query = new DbQuery("SELECT * FROM Applicants AS A WHERE A.ID = @ApplicantID",
new DbParam("@ApplicantID", applicantID)))
{
using (DataTable data = query.ExecuteDataTable())
{
if (data.Rows.Count > 0)
{
Applicant applicant = new Applicant(data.Rows[0]);
return new HttpResponseMessage()
{
Content = new StringContent(applicant.ToJson(), Encoding.UTF8, "text/html")
};
}
}
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
catch (Exception ex)
{
Methods.ProcessException(ex);
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
public HttpResponseMessage Post(Applicant applicant)
{
if (applicant.Save())
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, applicant);
string uri = Url.Link("DefaultApi", new { id = applicant.ID });
response.Headers.Location = new Uri(uri);
return response;
}
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Error saving applicant");
}
}
}
我在我的 WebApiConfig 中有相同的默认路由,并确认我的控制器的编写方式与标准的 Web API 2 控制器匹配,具有读取、写入、更新方法。我试过使用 DefaultAction,我试过用 [HttpGet] 和 [AcceptVerbs] 装饰方法。每当我自己尝试通过浏览器或通过 ajax 访问 Get 时,我都会收到 405(不允许的方法)。
Ajax 测试:
$("#TestGetApplicantButton").click(function (e) {
e.preventDefault();
alert("Getting Applicant...");
$.ajax({
type: "GET",
url: "/api/Applicants/108",
contentType: "application/json; charset-utf-8",
dataType: "json",
success: function (data) {
$("#ResponseDiv").html(JSON.stringify(data));
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
Ajax 完美适用于所有其他控制器,显示返回的数据(示例:
我的路线:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
我在这里进行了 google 和检查,但似乎每个人都只对 POST、PUT 或 DELETE 有问题,所以我还没有找到答案。我还尝试删除控制器中的 POST 方法 - 这让我得到了 404(不是来自我的 404,我确认代码没有执行),这表明由于某种原因路由无法找到我的 get 方法完全。
您需要为 applicantID 参数添加一个默认值,因为您的路由的第一个参数标记为 RouteParameter.Optional
。
public HttpResponseMessage Get(int applicantID = 0)
这将确保您的 Get 方法签名与您的 "DefaultApi" 路由匹配。