2016-05-05 7 views
0

У меня есть веб-проект, который является ASp.net MVC, а мои контроллеры - контроллеры mvc для маршрутизации и api-контроллеров. Я использую Managed Extensibility Framework (MEF). , и я только что начал страницу входа в систему, у которой есть контроллер учетных записей mvc и cont account. при запуске страницы входа в систему и при отправке имени пользователя и пароля он вызывает контроллер api из углового контроллера, а затем он идет для конструктора контроллера api, а затем вызывает Dispose перед вызовом моего действия для входа, тогда страница с ошибкой ресурса не найдена Запрошенный URL:/аккаунт/Войти Мой Войти действие с помощью WebSecurity Class (WebMatrix.WebData)Экспортированный API API-интерфейса, расположенный перед вызовом действия

Вот мой BaseApi контроллер

public class ApiControllerBase : ApiController, IServiceAwareController 
    { 
     List<IServiceContract> _DisposableServices; 

     protected virtual void RegisterServices(List<IServiceContract> disposableServices) 
     { 
     } 

     void IServiceAwareController.RegisterDisposableServices(List<IServiceContract> disposableServices) 
     { 
      RegisterServices(disposableServices); 
     } 

     List<IServiceContract> IServiceAwareController.DisposableServices 
     { 
      get 
      { 
       if (_DisposableServices == null) 
        _DisposableServices = new List<IServiceContract>(); 

       return _DisposableServices; 
      } 
     } 

     protected void ValidateAuthorizedUser(string userRequested) 
     { 
      string userLoggedIn = User.Identity.Name; 
      if (userLoggedIn != userRequested) 
       throw new SecurityException("Attempting to access data for another user."); 
     } 

     protected HttpResponseMessage GetHttpResponse(HttpRequestMessage request, Func<HttpResponseMessage> codeToExecute) 
     { 
      HttpResponseMessage response = null; 

      try 
      { 
       response = codeToExecute.Invoke(); 
      } 
      catch (SecurityException ex) 
      { 
       response = request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message); 
      } 
      catch (FaultException<AuthorizationValidationException> ex) 
      { 
       response = request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message); 
      } 
      catch (FaultException ex) 
      { 
       response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); 
      } 
      catch (Exception ex) 
      { 
       response = request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); 
      } 

      return response; 
     } 
    } 

и вот мой счет Api контроллер

[Export] 
    [PartCreationPolicy(CreationPolicy.NonShared)] 
    [RoutePrefix("api/account")] 
    public class AccountApiController : ApiControllerBase 
    { 
     [ImportingConstructor] 
     public AccountApiController(ISecurityAdapter securityAdapter) 
     { 
      _SecurityAdapter = securityAdapter; 
     } 

     ISecurityAdapter _SecurityAdapter; 


     [HttpPost] 
     [Route("login")] 
     public HttpResponseMessage Login(HttpRequestMessage request, [FromBody]AccountLoginModel accountModel) 
     { 
      return GetHttpResponse(request,() => 
      { 
       HttpResponseMessage response = null; 

       bool success = _SecurityAdapter.Login(accountModel.LoginEmail, accountModel.Password, accountModel.RememberMe); 
       if (success) 
        response = request.CreateResponse(HttpStatusCode.OK); 
       else 
        response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized login."); 

       return response; 
      }); 
     } 


    } 

и я зарегистрировать мой MEF класса расширений, которые обрабатывают MEF в Глоба asax

AggregateCatalog catalog = new AggregateCatalog(); 
      catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly())); 
      CompositionContainer container = MEFLoader.Init(catalog.Catalogs); 

      DependencyResolver.SetResolver(new MefDependencyResolver(container)); // view controllers 
      GlobalConfiguration.Configuration.DependencyResolver = new MefAPIDependencyResolver(container); // web api controllers 

и здесь тоже моего MEF класса зависимостей распознавателя

public class MefAPIDependencyResolver : IDependencyResolver 
    { 
     public MefAPIDependencyResolver(CompositionContainer container) 
     { 
      _Container = container; 
     } 

     CompositionContainer _Container; 

     public IDependencyScope BeginScope() 
     { 
      return this; 
     } 

     public object GetService(Type serviceType) 
     { 
      return _Container.GetExportedValueByType(serviceType); 
     } 

     public IEnumerable<object> GetServices(Type serviceType) 
     { 
      return _Container.GetExportedValuesByType(serviceType); 
     } 

     public void Dispose() 
     { 
     } 
    } 

я потерял сюжет. Заранее благодарю за любую помощь.

ответ

0

OOps это моя ошибка. речь шла о форме HTML, который имеет действие на контроллер и MVC не существует поэтому вместо

<form class="loginForm" action="@Url.Action("Login","Account")" method="post" name="loginForm"> 

так что заменить его

<form class="loginForm" name="loginForm"> <!--Without action--> 
    <!--and submit button--> 
<button type="submit" class="btn blue pull-right" ng-click="login()">