簡體   English   中英

REST 服務錯誤 405:方法不允許

[英]REST Service Error 405: Method not allowed

我的 Get 工作正常,但我的更新和刪除給了我 405 錯誤。 這是我的 Web.config 和控制器。 抱歉格式不正確。 我嘗試了很多不同的方法,但我不確定為什么會出現 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("api/responseitems/")] 作為控制器,然后使用 [Route("api/responseitems/{id}")] 作為方法,但同樣的 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 }
        );
        }
    }

我認為問題在於您的應用程序的調用機制。 您可以在調用 API 時使用正確的 Http 動詞嗎?

或者將您的完整端點與您的方法類型放在一起,以便我可以進一步幫助您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM