ApiController无法使用404期望

时间:2018-11-30 08:20:17

标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-web-api-routing

我有一个从System.Web.Http.ApiController(使用Nuget包Microsoft.AspNet.WebApi.Core.5.2.3)派生的控制器。

我在控制器类上使用了RoutePrefix,在操作上使用了Route Attribute。

我配置了两条路线。一个在WebAPiConfig(HttpRouteCollection)中,另一个在RouteConfig(System.Web.Routing.RouteCollection)中

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

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

当我遇到邮递员的请求时。我收到404错误代码。奇怪的是堆栈跟踪是:

[HttpException]: The controller for path '/api/Account/IsAuthorized' was not found or does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

下面是控制器代码:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    /// <summary>
    /// Determines whether this instance is authorized.
    /// </summary>
    /// <returns>send whether the user is authorized or not</returns>
    [AllowAnonymous]
    [Route("IsAuthorized")]
    [HttpGet]
    public HttpResponseMessage IsAuthorized()
    {
        return Request.CreateResponse(User.Identity.IsAuthenticated);
        ////return true;
    }
}

Global.asax注册顺序

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        UnityConfig.RegisterComponents(HttpConfiguration.Config);
        WebApiConfig.Register(HttpConfiguration.Config);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

为什么框架尝试通过System.Web.Mvc.DefaultControllerFactory.GetControllerInstance初始化控制器

在同一API项目中,我有另一个由System.Web.Mvc.Controller删除的控制器,并且运行良好。

任何指针都会对我有很大帮助。

2 个答案:

答案 0 :(得分:0)

只需在定义路线之前添加以下内容即可:

config.MapHttpAttributeRoutes();

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

更多信息6.3

答案 1 :(得分:0)

添加

GlobalConfiguration.Configure(WebApiConfig.Register);

代替

WebApiConfig.Register(Orbit.WebApi.Extensions.Startup.Config);

为我工作。对于WebAPI控制器,我必须弄清楚这两行之间的真正区别是什么。

我记得我在某个地方读到,这只是一种改进。但这可能会带来很大的变化,我不知道。

如果有人能对此有所介绍,我将非常感谢。