为什么我不允许使用错误405方法?

时间:2016-08-10 22:03:56

标签: c# visual-studio http asp.net-web-api2

我正在使用Visual Studio 2013中的Web Api 2创建SharePoint 2013 API.SharePoint 2013在本地运行,并且我具有对SharePoint网站的完全管理员访问权限。

以下是我的客户端Ajax调用:

$(document).ready(function() {
    $.support.cors = true;
    $.ajax({
        url: 'http://localhost:8400/api/SharePointAPI/GetItems',
        cache: false,
        type: 'POST',
        dataType: 'json',
        params: {},
        contentType: 'application/json; charset=utf-8'
    }).success(function(data) {
        $.each(data, function () {
            var $row = $(document.createElement("tr"));

            //Inner each creates the cells in the table
            $.each(this, function (i, v) {
                $td = $(document.createElement("td")).text(v);
                $row.append($td);
            });
            // Appends the row to the table body.
            $tbody.append($row);
        });
    }).error(function(xhr) {
        alert(xhr.responseText);
    });
});

我的服务器端代码如下:

WebApiContextFilterAttribute.cs:

public class WebAPIContextFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (actionContext == null)
        {
            throw new ArgumentNullException("actionContext");
        }

        Uri redirectUrl;
        switch (SharePointApiControllerContextProvider.CheckContextStatus(actionContext.ControllerContext, out redirectUrl))
        {
            case ContextStatus.Ok:
                return;
            case ContextStatus.NotOk:
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.MethodNotAllowed, "Context couldn't be created: access denied");
                break;
        }
    }
}

的Global.asax.cs:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

    protected void Application_BeginRequest()
    {
        if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
        {
            Response.Flush();
            Response.End();
        }
    }
}

WebApiConfig.cs:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

控制器:

[System.Web.Script.Services.ScriptService]
public class SharePointApiController : ApiController
{
    //[HttpPut]
    //public void Register(WebAPIContext sharePointServiceContext)
    //{
    //    WebAPIHelper.AddToCache(sharePointServiceContext);
    //}

    [WebAPIContextFilter]
    //[Route("api/SharePointAPI/GetItems")]
    [HttpPost]
    public IHttpActionResult GetItems()
    {
        using (var clientContext = WebAPIHelper.GetClientContext(ControllerContext))
        {
            ICollection<ListItem> results = new List<ListItem>();
            if (clientContext != null)
            {
                // your code goes here
                List docsList = clientContext.Web.Lists.GetByTitle("Documents");

                CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
                ListItemCollection items = docsList.GetItems(query);

                clientContext.Load(items);
                clientContext.ExecuteQuery();

                foreach (ListItem item in items)
                {
                    results.Add(item);
                }
                return Ok(results);
            }
            else
            {
                // your code goes here
                return Content(HttpStatusCode.BadRequest, "The server could not process your request.");
            }
        }
    }
}

我的web.config包含以下内容:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost:8401" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="POST, PUT, OPTIONS" />
  </customHeaders>
</httpProtocol>

我的问题很简单,当我尝试调用API调用时,为什么我会收到405错误,说明该方法是不允许的? (仅供参考,它是由WebAPIContextFilterAttribute.cs中的代码触发的,可能是因为cookie问题或null参数。)

谢谢。

0 个答案:

没有答案