c# - System.Web.Http.ApiController.get_Request() 中缺少方法

标签 c# asp.net-web-api

我有一个 Controller 。

    public sealed class AccountsController : BaseApiController
    {
        private readonly IDatabaseAdapter _databaseAdapter;
        public AccountsController(IDatabaseAdapter databaseAdapter)
        {
            _databaseAdapter = databaseAdapter;
        }

        [AllowAnonymous]
        [Route("create")]
        public async Task<IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            if (! await _databaseAdapter.DoesAgentExist(createUserModel.UserName))
                return BadRequest();
            if (await _databaseAdapter.DoesAgentHaveAccount(createUserModel.UserName))
                return BadRequest();

            // Create account.
            var password = PasswordHelper.GeneratePassword(32);
            createUserModel.Password = password;
            createUserModel.ConfirmPassword = password;
            var user = new ApplicationUser
            {
                UserName = createUserModel.UserName,
            };
            var addUserResult = await AppUserManager.CreateAsync(user, createUserModel.Password);
            if (!addUserResult.Succeeded)
                return GetErrorResult(addUserResult);
            var locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));
            return Created(locationHeader, ModelFactory.Create(user));
        }
    }

当我将以下 fiddler 发送到创建方法时。

http://localhost:59430/api/accounts/create User-Agent: Fiddler

Content-Type: application/json Accept: application/json Host: localhost:59430 Content-Length: 106

{ "UserName":"a.xxxxx", "Password":"xxxxxx", "ConfirmPassword":"xxxxxx", }

它归结为以下行:

var addUserResult = await AppUserManager.CreateAsync(user, createUserModel.Password);

然后出现如下异常

{ "message": "An error has occurred.", "exceptionMessage": "Method not found: 'System.Net.Http.HttpRequestMessage System.Web.Http.ApiController.get_Request()'.", "exceptionType": "System.MissingMethodException", "stackTrace": " at WebAuth.Controllers.BaseApiController.get_AppUserManager()\r\n at WebAuth.Controllers.AccountsController.d__3.MoveNext() in C:\Users\stuarts\Documents\Visual Studio 2017\Projects\WebAuth\WebAuth\Controllers\AccountsController.cs:line 76\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Threading.Tasks.TaskHelpersExtensions.d__3`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()" }

有人知道这是怎么回事吗?我不知道为什么它找不到那个方法。

我的 bin 文件夹包含

系统.Web.Http.dll 系统.Web.Http.Owin.dll 系统.Net.Http.dll

应用程序用户管理器

public sealed class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store)
        {
        }
        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
                                                    IOwinContext context)
        {
            var appDbContext = context.Get<ApplicationDbContext>();
            var appUserManager = new ApplicationUserManager(new UserStore<ApplicationUser>(appDbContext));

            appUserManager.UserValidator = new UserValidator<ApplicationUser>(appUserManager)
            {
                AllowOnlyAlphanumericUserNames = true,
                RequireUniqueEmail = false,
            };
            appUserManager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 12,
                RequireNonLetterOrDigit = true,
                RequireUppercase = true,
                RequireLowercase = true,
                RequireDigit = true
            };
            appUserManager.MaxFailedAccessAttemptsBeforeLockout = 3;
            appUserManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromHours(1);
            return appUserManager;
        }
    }

基础API Controller

public class BaseApiController : ApiController
    {
        private ModelFactory _modelFactory;
        private readonly ApplicationUserManager _applicationUserManager = null;
        protected ApplicationUserManager AppUserManager => _applicationUserManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
        protected ModelFactory ModelFactory => _modelFactory ?? (_modelFactory = new ModelFactory(Request, AppUserManager));
        protected IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
                return InternalServerError();

            if (result.Succeeded) return null;

            if (result.Errors != null)
                foreach (var error in result.Errors)
                    ModelState.AddModelError(string.Empty, error);

            if (ModelState.IsValid)
                return BadRequest();

            return BadRequest(ModelState);
        }
        private readonly ApplicationRoleManager _appRoleManager = null;
        protected ApplicationRoleManager AppRoleManager => _appRoleManager ?? Request.GetOwinContext().GetUserManager<ApplicationRoleManager>();
    }

最佳答案

我找到了解决办法。

当我构建时,输出窗口中有构建警告,但没有显示在主错误/警告窗口中。

他们要处理程序集冲突并建议将程序集重定向放在 web.Config 中。

一旦我完成所有这些(大约 80 个),它现在就可以工作了。

例如

      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
      </dependentAssembly>

关于c# - System.Web.Http.ApiController.get_Request() 中缺少方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46451247/

相关文章:

c# - 使用 FastReport.net 和 asp.net 导出 pdf

c# - 基本类型的必需属性没有意义

asp.net-mvc - asp.net mvc web api项目中的MessageHandlers vs Filters

c# - Web api 操作参数将空字符串参数转换为 null

c# - 在应用程序设置中存储 Dictionary<string,string>

c# - 如何在 WPF 中显示按钮被单击(按下)?

c# - AutoMapper:映射子集合

c# - 如何从派生类的实例中调用基类非默认构造函数?

c# - 如何从Request对象中获取HttpContent?

javascript - 如何从javascript json接收WebAPI中的字典