我有一个问题,我不知道为什么会出现问题。
我想要的是在我的web api中调用一个方法,httpOptions动词应该返回一个HttpOkStatus,但它会返回404错误。只有在我贴上标签时才会发生这种情况
[Route("MyRoute")]
,否则效果很好。
我的问题是,当我把标签放在上面时,为什么它不起作用?。
我有这段代码
[Authorize]
[RoutePrefix("api/MergedSchemas")]
public class MergedSchemasController : ApiController
{
[HttpGet]
[Route("Schemas")]
public HttpResponseMessage GetSchemas(string formName)
{
//Some code
}
}
在Global.asax中我有这段代码:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.MessageHandlers.Add(new OptionsHttpMessageHandler());
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
public class OptionsHttpMessageHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Options)
{
var apiExplorer =
GlobalConfiguration.Configuration.Services.GetApiExplorer();
var controllerRequested = request.GetRouteData().Values["controller"] as string;
var supportedMethods = apiExplorer.ApiDescriptions.Where(d =>
{
var controller = d.ActionDescriptor.ControllerDescriptor.ControllerName;
return string.Equals(
controller, controllerRequested, StringComparison.OrdinalIgnoreCase);
})
.Select(d => d.HttpMethod.Method)
.Distinct();
if (!supportedMethods.Any())
return Task.Factory.StartNew(
() => request.CreateResponse(HttpStatusCode.NotFound));
return Task.Factory.StartNew(() =>
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Headers.Add("Access-Control-Allow-Methods", string.Join(",", supportedMethods));
return resp;
});
}
return base.SendAsync(request, cancellationToken);
}
}
我打电话的是:/api/MergedSchemas/Schemas?formName=frmBCOSEG
谢谢!