Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

c# - MIssing method in System.Web.Http.ApiController.get_Request()

I have a 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));
        }
    }

When I send the following fiddler to the create method.

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", }

It gets down to the following line:

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

Then the following exception occurs

{ "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() at WebAuth.Controllers.AccountsController.d__3.MoveNext() in C:UsersstuartsDocumentsVisual Studio 2017ProjectsWebAuthWebAuthControllersAccountsController.cs:line 76 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Threading.Tasks.TaskHelpersExtensions.d__3`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()" }

Anyone know what is going on? I have no idea why it can't find that method.

My bin folders contains

System.Web.Http.dll System.Web.Http.Owin.dll System.Net.Http.dll

ApplicationUserManager

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;
        }
    }

BaseApiController

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>();
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found a solution to this.

When I was building there was build warnings going to the output window but not showing in the main error / warning window.

They were to do with assembly conflicts and said recommend putting the assembly redirect in the web.Config.

Once I had went through them all (around 80) it now works.

e.g.

      <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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...