微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

GET上的C#Web API 405错误

经过十年的桌面开发,我对宁静的API都是全新的.我有点困惑为什么我要为控制器尝试GET 405.

我的控制器:

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适用于所有其他控制器,显示返回的数据(例如:

Tests Work!

,它甚至调用此控制器上的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"));
    }

我在谷歌上搜索并检查过,但每个人似乎只有POST,PUT或DELETE的问题,所以我没有找到答案.我也尝试删除控制器中的POST方法 – 这让我得到了404(不是来自我的404,我确认代码没有执行),这表明由于某种原因路由无法找到我的get方法所有.

解决方法:

您需要为applicantID参数添加一个认值,因为您的路由的第一个参数标记为RouteParameter.Optional.

public HttpResponseMessage Get(int applicantID = 0)

这将确保您的Get方法签名与您的“DefaultApi”路由匹配.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐