WebApi 2 Http Post 405"请求的资源不支持http方法' POST'"

时间:2016-07-15 13:29:10

标签: c# asp.net asp.net-web-api cors

我看了所有StackOverflow,但没有为我的案例找到解决方案 我有405个HttpStatusCode调用API / Regions / Create动作 这是我的baseController方法:

 [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>

有什么建议可能出错吗?

3 个答案:

答案 0 :(得分:1)

您应该在POST请求中调用API / Regions,而不是API / Regions / Create,除非您在操作的Route属性中指定API / Regions / Create。 WebApi将知道要搜索哪种方法来处理请求。

答案 1 :(得分:0)

要让框架识别继承的属性,您需要按照概述here覆盖DefaultDirectRouteProvider

并用于答案

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());

希望这有帮助

答案 2 :(得分:0)

您可以尝试在web.config中将行更改为以下内容:

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