我已经看过扔掉所有的StackOverflow,但是没有找到适合我的情况的解决方案
我有405个HttpStatusCode调用API /区域/创建动作
这是我的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>
有什么建议可能有什么问题吗?
最佳答案
除非在操作的Route
属性中指定API / Regions / Create,否则应在POST请求上调用API / Regions,而不是API / Regions / Create。 WebApi将知道搜索哪种方法来处理请求。