REST服务错误405:不允许使用方法

时间:2017-06-15 20:58:36

标签: c# asp.net rest asp.net-web-api httpresponsemessage

我的Get Works完美,但我的更新和删除给了我405错误。 这是我的Web.config和Controller。抱歉格式不正确。我尝试了很多不同的东西,但我不确定为什么我会得到405个错误。 我的应用程序与我的其他REST服务一起工作,所以我知道它可以执行CRUD,问题是我的服务。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
        <add key="Username" value="Xamarin" />
        <add key="Password" value="Pa$$w0rd" />
    </appSettings>
    <system.web>
        <compilation debug="true" targetFramework="4.5">
            <assemblies>
                <add assembly="System.Net.Http.WebRequest, Version=4.0.0.0, 
    Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
            </assemblies>
        </compilation>
        <httpRuntime targetFramework="4.5" />
        <httpModules>
            <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule,Microsoft.AI.Web" />
        </httpModules>
    </system.web>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
                <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
            <remove name="WebDAVModule"/>
            <remove name="ApplicationInsightsWebTracking" />
            <add name="ApplicationInsightsWebTracking" 
  type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
        </modules>
        <handlers>
            <remove name="WebDAV" />
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
        <directoryBrowse enabled="true" />
        <validation validateIntegratedModeConfiguration="false" />
    </system.webServer>

这是我的控制器

public class ResponseItemsController : BaseApiController
{
    static readonly IwellService wellService = new wellService(new 
    wellRepository());

    [HttpGet]
    [BasicAuthentication(RequireSsl = false)]
    public HttpResponseMessage Get()
    {
        return base.BuildSuccessResult(HttpStatusCode.OK, 
        wellService.GetData());
    }

    [HttpPost]
    [BasicAuthentication(RequireSsl = false)]
    public HttpResponseMessage Create([FromBody]ResponseItem item)
    {
        try
        {
            if (item == null ||
                string.IsNullOrWhiteSpace(item.Name__c) ||
                string.IsNullOrWhiteSpace(item.Question_1__c))
            {
                return base.BuildErrorResult(HttpStatusCode.BadRequest, ErrorCode.wellItemNameAndNotesRequired.ToString());
            }

            // Determine if the ID already exists
            var itemExists = wellService.DoesItemExist(item.ID);
            if (itemExists)
            {
                return base.BuildErrorResult(HttpStatusCode.Conflict, ErrorCode.wellItemIDInUse.ToString());
            }
            wellService.InsertData(item);
        }
        catch (Exception)
        {
            return base.BuildErrorResult(HttpStatusCode.BadRequest, ErrorCode.CouldNotCreateItem.ToString());
        }

        return base.BuildSuccessResult(HttpStatusCode.Created);
    }

    [HttpPut]
    [BasicAuthentication(RequireSsl = false)]
    public HttpResponseMessage Edit(string id, [FromBody]ResponseItem item)
    {
        try
        {
            if (item == null ||
                string.IsNullOrWhiteSpace(item.Name__c) ||
                string.IsNullOrWhiteSpace(item.Mentor_name__c))
            {
                return base.BuildErrorResult(HttpStatusCode.BadRequest, ErrorCode.wellItemNameAndNotesRequired.ToString());
            }

            var wellItem = wellService.Find(id);
            if (wellItem != null)
            {
                wellService.UpdateData(item);
            }
            else
            {
                return base.BuildErrorResult(HttpStatusCode.NotFound, ErrorCode.RecordNotFound.ToString());
            }
        }
        catch (Exception)
        {
            return base.BuildErrorResult(HttpStatusCode.BadRequest, ErrorCode.CouldNotUpdateItem.ToString());
        }

        return base.BuildSuccessResult(HttpStatusCode.NoContent);
    }

    [HttpDelete]
    [BasicAuthentication(RequireSsl = false)]
    public HttpResponseMessage Delete(string id)
    {
        try
        {
            var wellItem = wellService.Find(id);
            if (wellItem != null)
            {
                wellService.DeleteData(id);
            }
            else
            {
                return base.BuildErrorResult(HttpStatusCode.NotFound, ErrorCode.RecordNotFound.ToString());
            }
        }
        catch (Exception)
        {
            return base.BuildErrorResult(HttpStatusCode.BadRequest, ErrorCode.CouldNotDeleteItem.ToString());
        }

        return base.BuildSuccessResult(HttpStatusCode.NoContent);
    }
}

}

这是我的路由WebApiconfig / Routeconfig。我尝试使用[Route(&#34; api / responseitems /&#34;)]作为控制器,然后[路由(&#34; api / responseitems / {id}&#34;)]方法但405错误的问题相同。我写的例外情况是代码只有404,400,200。

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
        // Web API routes
        config.MapHttpAttributeRoutes();

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


public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new {id = UrlParameter.Optional }
        );
        }
    }

1 个答案:

答案 0 :(得分:0)

我认为问题出在应用程序中的调用机制。您可以在调用API时使用正确的Http动词吗?

或者将您的完整端点与您的方法类型一起放置,以便我进一步帮助您。