经过十年的桌面开发,我对宁静的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访问浏览器时,我都会获得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适用于所有其他控制器,显示返回的数据(例如:,它甚至可以调用此控制器上的Post方法。但我不能让我上班。我不知道我哪里会出错。
我的路线:
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方法< em> at 。
答案 0 :(得分:4)
您需要为applicantID参数添加默认值,因为您的路线的第一个参数标记为input file libgs_arm64_release.a is not a fat file
Non-fat file: libgs_arm64_release.a is architecture: x86_64
。
RouteParameter.Optional
这将确保您的Get方法签名与您的“DefaultApi”路由匹配。