[英]WebApi 2 Http Post 405 “The requested resource does not support http method 'POST'”
I have looked throw all StackOverflow, but didn`t find solution for my case I have 405 HttpStatusCode calling API/Regions/Create action Here is my baseController method:我已经查看了所有 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区域控制器.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 config: 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:全球.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);
}
}
}
and Web.Config:和 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>
Any suggestions what might be wrong?任何建议可能有什么问题?
You should call API/Regions on your POST request, not API/Regions/Create, unless you specify API/Regions/Create in a Route
attribute on the action.您应该在 POST 请求上调用 API/Regions,而不是 API/Regions/Create,除非您在操作的
Route
属性中指定 API/Regions/Create。 WebApi will know what method to search for to handle the request. WebApi 将知道要搜索什么方法来处理请求。
To get the framework to recognize the inherited attributes you need to override the DefaultDirectRouteProvider
as outlined here要获得承认继承属性的框架,你需要重写
DefaultDirectRouteProvider
所概述这里
and used in an answer here并在此处的答案中使用
WebAPI controller inheritance and attribute routing WebAPI 控制器继承和属性路由
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);
}
}
and apply that to the web api configuration.并将其应用于 web api 配置。
// Attribute routing. (with inheritance)
config.MapHttpAttributeRoutes(new WebApiCustomDirectRouteProvider());
Hope this helps希望这有帮助
您可以尝试将 web.config 中的行更改为以下内容:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.