2016-07-15 173 views
2

我已經看過拋出所有的StackOverflow,但沒有找到我的案例的解決方案 我有405 HttpStatusCode調用API /地區/創建操作 這裏是我的baseController方法:WebApi 2 Http Post 405「請求的資源不支持http方法'POST'」

[HttpPost] 
     public virtual IHttpActionResult Create([FromBody]T entity) 
     { 
      try 
      { 
       repository.Create(entity); 

       return Ok(entity); 
      } 
      catch (HttpException e) 
      { 
       return new ExceptionResult(e, this); 
      } 
     } 

RegionController.cs

public class RegionsController : BaseController<Region, RegionRepository> 
{ 
    public RegionsController() 
    { } 
    public RegionsController(RegionRepository _repository) 
    { 
     RegionRepository repository = new RegionRepository();//_repository; 
    } 

    RegionRepository repository = new RegionRepository(); 

    [HttpGet] 
    [Route("api/regions/{name}")] 
    public IHttpActionResult Get(string name) 
    { 
     try 
     { 
      var region = repository.Get(name); 

      return Ok(region); 
     } 
     catch (HttpException e) 
     { 
      return new ExceptionResult(e, this); 
     } 
    } 
} 

的WebAPI配置:

 public static class WebApiConfig 
    { 
     public static void Register(HttpConfiguration config) 
     { 
      // Web API configuration and services 
      // Configure Web API to use only bearer token authentication. 
      // Web API configuration and services 
      var cors = new EnableCorsAttribute("*", "*", "*"); 
      config.EnableCors(cors); 


      config.SuppressDefaultHostAuthentication(); 
      config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 


      // Web API routes 
      config.MapHttpAttributeRoutes(); 

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

的Global.asax:

public class WebApiApplication : System.Web.HttpApplication 
     { 
      private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); 
      protected void Application_Start() 
      { 
       logger.Info("Application Start"); 
       AreaRegistration.RegisterAllAreas(); 
       GlobalConfiguration.Configure(WebApiConfig.Register); 
       FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
       RouteConfig.RegisterRoutes(RouteTable.Routes); 
       BundleConfig.RegisterBundles(BundleTable.Bundles); 

       //GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler()); 
      } 

      //protected void Application_BeginRequest(object sender, EventArgs e) 
      //{ 
      // HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 
      // //if (HttpContext.Current.Request.HttpMethod == "OPTIONS") 
      // //{ 
      //  HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE"); 

      //  HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); 
      //  HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); 
      //  HttpContext.Current.Response.End(); 
      // // } 
      //} 

      private void Application_Error(object sender, EventArgs e) 
      { 

       var lastException = Server.GetLastError(); 

       NLog.LogManager.GetCurrentClassLogger().Error(lastException); 

      } 


     } 
} 

和程序Web.Config:

 <system.web> 
    <authentication mode="None" /> 
    <compilation debug="true" targetFramework="4.5.2" /> 
    <httpRuntime targetFramework="4.5.2" /> 
    <httpModules> 
     <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" /> 
    </httpModules> 
    </system.web> 
    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"> 
     <remove name="WebDAVModule" /> 
    </modules> 
    <handlers> 
     <remove name="WebDAV" /> 
     <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
     <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" /> 
    </handlers> 

任何建議可能是什麼問題?

+0

是你實現控制器創建方法? –

回答

1

除非在操作的Route屬性中指定API /區域/創建,否則應該在POST請求上調用API /區域,而不是API /區域/創建。 WebApi會知道搜索什麼方法來處理請求。

+0

非常感謝,它的工作:) –

+0

但爲什麼有405錯誤,而不是404? –

+1

你有一條路由'[Route(「api/regions/{name}」)]'作爲HttpGet路由。我認爲框架首先匹配請求的路由,然後檢查是否允許POST,而不是首先查找所有POST可用路由,然後檢查哪些路由匹配。 – martennis

0

爲了讓框架認出你需要重寫DefaultDirectRouteProvider所概述here

和使用這裏的答案

WebAPI controller inheritance and attribute routing

public class WebApiCustomDirectRouteProvider : DefaultDirectRouteProvider { 
    protected override System.Collections.Generic.IReadOnlyList<IDirectRouteFactory> 
     GetActionRouteFactories(System.Web.Http.Controllers.HttpActionDescriptor actionDescriptor) { 
     // inherit route attributes decorated on base class controller's actions 
     return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true); 
    } 
} 

繼承的屬性並應用到Web api配置。

// Attribute routing. (with inheritance) 
config.MapHttpAttributeRoutes(new WebApiCustomDirectRouteProvider()); 

希望這有助於

0

你能嘗試改變線,下方在你的web.config:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" /> 
相關問題