MVC控制器-异步操作方法返回一个Task,该Task无法同步执行

时间:2019-02-01 11:06:11

标签: c# model-view-controller

运行以下控制器时,我收到上述错误。我有一个不会导致此错误的类似控制器。

仅当我在视图(PostLandingFormEnquiry)中提交表单时,才会发生错误。

堆栈跟踪点将“ LandingPage”作为问题。

您能指出导致错误的原因吗?

namespace TSW.Web.Controllers
{
public class LandingPageSurfaceController : SurfaceController
{
    private readonly ISitePageFactory _pageFactory = null;
    private readonly IOrderService _orderService = null;
    private readonly IConfiguration _config = null;

    public LandingPageSurfaceController(ISitePageFactory pageFactory, IOrderService orderService,
        IConfiguration config)
    {
        _pageFactory = pageFactory;
        _orderService = orderService;
        _config = config;
    }

    [ChildActionOnly]
    public ActionResult ShowLandingEnquiryForm(LandingPageVM Model)
    {
        var EventList = new List<SelectListItem>();

        if (Model.Events.Any())
        {
            foreach (var events in Model.Events)
            {
                var Dropdown = events.Start.ToShortDateString() + " - " + "£" + events.NormalPrice.Amount + " + VAT";
                var DropdownClean = Dropdown.Remove(Dropdown.IndexOf("."));
                EventList.Add(new SelectListItem
                {
                    Value = events.Id.ToString(),
                    Text = DropdownClean
                });
            };
        }
        return PartialView("_LandingEnquiryForm", new LandingEnquiryForm { EventList = EventList });
    }

    [ChildActionOnly]
    public ActionResult ShowContactFormFooter()
    {
        return PartialView("_ContactFormFooter", new ContactForm { });
    }

    [HttpPost]
    public async Task<ActionResult> PostLandingEnquiryForm(LandingEnquiryForm enquiryForm)
    {
        var homepage = _pageFactory.GetCurrentHomepage();
        if (!ModelState.IsValid)
        {
            return CurrentUmbracoPage();
        }
        await _orderService.SaveLandingEnquiry(CreateLandingPageForm(enquiryForm));
        return RedirectToUmbracoPage(homepage.EnquirySuccessPage);
        /*string EncodedResponse = Request.Form["g-Recaptcha-Response"];
        bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false);

        if (IsCaptchaValid)
        {
            await _orderService.SaveCourseEnquiry(CreateCourseEnquiryForm(contactForm));
            return RedirectToUmbracoPage(homepage.EnquirySuccessPage);
        }
        else
        {
            return RedirectToCurrentUmbracoPage();
        }*/
    }

    private LandingPageRequest CreateLandingPageForm(LandingEnquiryForm enquiryForm)
    {
        HttpContext context = System.Web.HttpContext.Current;
        var campaign = (string)(context.Session["gclid"]);
        var opps = new List<Opportunity>();
        opps.Add(new Opportunity()
        {
            EventId = new EventBooking
            {
                Id = enquiryForm.EventId
            },
            Quantity = 1,
            TaxType = new TaxType
            {
                Id = 1,
                Name = "UK VAT",
                Rate = 20
            },
            RegionCode = "WAL",
        });

        DateTime d = DateTime.UtcNow.Date;
        var landingEnquiry = new LandingPageRequest
        {
            Opportunities = opps,
            Name = string.Format("Landing page Enquiry - {1} - {0}", enquiryForm.CompanyName, d.ToString("D")),
            SourceType = _config.OpportunitySourceType,
            CompanyId = _config.OpportunityCompanyId,
            Step = _config.EnquiryStepId,
            Currency = _config.OpportunityCurrency,
            UserId = _config.EnquiryUserId,
            OpportunityContact =
                new Contact
                {
                    CompanyName = enquiryForm.CompanyName,
                    Name = enquiryForm.ContactName,
                    Email = enquiryForm.ContactEmail,
                    Phone = enquiryForm.ContactNo,
                    OrderDateTime = DateTime.Now,
                    PPC = campaign,
                },

            MarketingActivityId = _config.EnquiryMarketingActivityId

        };
        return landingEnquiry;
    }

}
public class LandingPageController : BaseRenderController<LandingPageDT>
{
    private readonly ISitePageFactory _pageFactory = null;
    private readonly IConfiguration _config = null;
    private readonly IEventService _eventService = null;

    public LandingPageController()
        : this(
            ServiceLocator.Current.GetInstance<ISitePageFactory>(),
            ServiceLocator.Current.GetInstance<IEventService>(),
            ServiceLocator.Current.GetInstance<IConfiguration>())
    {
    }

    public LandingPageController(ISitePageFactory pageFactory, IEventService eventService, IConfiguration config)
    {
        _config = config;
        _pageFactory = pageFactory;
        _eventService = eventService;
    }

    [OutputCache(CacheProfile = "Cache1Hour")]
    public async Task<ActionResult> LandingPage()
    {
        var homepage = _pageFactory.GetCurrentHomepage();
        var model = Mapper.Map<LandingPageVM>(CurrentContent);
        model.Email = homepage.ContactEmail;
        model.PhoneNumber = homepage.HeaderPhoneNumber;

        model.InnerPageHeader.ShowHeading = true;
        model.InnerPageHeader.Title = model.PageTitle;
        model.InnerPageHeader.Duration = model.Duration;
        var sources = new List<string>();
        foreach (var source in model.SourceTypes)
        {
            sources.Add(source.SourceName);
        }
        if (CurrentContent.Graphic != 0)
        {
            model.InnerPageHeader.Graphic = Mapper.Map<CtaItem>(CurrentContent.Graphic);
        }
        ViewBag.SourceList = sources.Select(f => new SelectListItem() { Value = f, Text = f, });
        try
        {
            model.Events = await _eventService.GetEventsForCourse(CurrentContent.AdministrateId);
        }
        catch (Exception ex)
        {
            model.Events = new StaticPagedList<Event>(Enumerable.Empty<Event>(), 1, 1, 0);
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
        }
        return View(model);
    }

}
}

编辑1:堆栈跟踪

[InvalidOperationException: The asynchronous action method 'LandingPage' returns a Task, which cannot be executed synchronously.]
   System.Web.Mvc.Async.TaskAsyncActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +140
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +80
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +454
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +454
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +454
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +973
   System.Web.Mvc.Controller.ExecuteCore() +128
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +235
   Umbraco.Web.Mvc.UmbracoPageResult.ExecuteControllerAction(ControllerContext context, IController controller) +104
   Umbraco.Web.Mvc.UmbracoPageResult.ExecuteResult(ControllerContext context) +385
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +88
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +775
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +775
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +775
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +188
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +602
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +128

有效的控制器

namespace TSW.Web.Controllers
{

    public class CourseEnquiryPageSurfaceController : SurfaceController
    {
        private readonly ISitePageFactory _pageFactory = null;
        private readonly IOrderService _orderService = null;
        private readonly IConfiguration _config = null;

        public CourseEnquiryPageSurfaceController(ISitePageFactory pageFactory, IOrderService orderService,
            IConfiguration config)
        {
            _pageFactory = pageFactory;
            _orderService = orderService;
            _config = config;
        }

        [ChildActionOnly]
        public ActionResult ShowCourseEnquiryForm()
        {
            return PartialView("_CourseEnquiryForm", new CourseEnquiryForm {});
        }

        [ChildActionOnly]
        public ActionResult ShowContactFormFooter()
        {
            return PartialView("_ContactFormFooter", new ContactForm { });
        }

        [HttpPost]
        public async Task<ActionResult> PostCourseEnquiryForm(CourseEnquiryForm contactForm)
        {
            var homepage = _pageFactory.GetCurrentHomepage();
            if (!ModelState.IsValid)
            {
                return CurrentUmbracoPage();
            }

            string EncodedResponse = Request.Form["g-Recaptcha-Response"];
            bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false);

            if (IsCaptchaValid)
            {
                await _orderService.SaveCourseEnquiry(CreateCourseEnquiryForm(contactForm));
                return RedirectToUmbracoPage(homepage.EnquirySuccessPage);
            }
            else
            {
                return RedirectToCurrentUmbracoPage();
            }
        }

        private EnquiryRequest CreateCourseEnquiryForm(CourseEnquiryForm contactForm)
        {
            HttpContext context = System.Web.HttpContext.Current;
            var campaign = (string)(context.Session["gclid"]);
            var opps = new List<Interest>();
            opps.Add(new Interest()
            {
                CourseId = new CourseBooking
                {
                    Id = contactForm.Course
                },
                Quantity = contactForm.Quantity,
                TaxType = new TaxType
                {
                    Id = 1,
                    Name = "UK VAT",
                    Rate = 20
                },
                RegionCode = "WAL",
            });

            DateTime d = DateTime.UtcNow.Date;
            var courseEnquiry = new EnquiryRequest
            {
                Opportunities = opps,
                Name = string.Format("Course Enquiry - {1} - {0}", contactForm.CompanyName, d.ToString("D")),
                SourceType = _config.OpportunitySourceType,
                CompanyId = _config.OpportunityCompanyId,
                Step = _config.EnquiryStepId,
                Currency = _config.OpportunityCurrency,
                UserId = _config.EnquiryUserId,
                OpportunityContact =
                    new Contact
                    {
                        CompanyName = contactForm.CompanyName,
                        Name = contactForm.Name,
                        Email = contactForm.Email,
                        Phone = contactForm.ContactNo,
                        WebSource = contactForm.Source,
                        OrderDateTime = DateTime.Now,
                        OtherCourses = contactForm.OtherCourses,
                        PPC = campaign,
                    },

                MarketingActivityId = _config.EnquiryMarketingActivityId

            };
            return courseEnquiry;
        }

    }

    public class CourseEnquiryPageController : BaseRenderController<CourseEnquiryPageDT>
    {
        private readonly ISitePageFactory _pageFactory = null;
        private readonly IConfiguration _config = null;

        public CourseEnquiryPageController()
            : this(
                ServiceLocator.Current.GetInstance<ISitePageFactory>(),
                ServiceLocator.Current.GetInstance<IConfiguration>())
        {
        }

        public CourseEnquiryPageController(ISitePageFactory pageFactory, IConfiguration config)
        {
            _config = config;
            _pageFactory = pageFactory;
        }

        [OutputCache(CacheProfile = "Cache1Hour")]
        public ActionResult CourseEnquiry()
        {
            var model = Mapper.Map<CourseEnquiryVM>(CurrentContent);
            model.InnerPageHeader.ShowHeading = true;
            model.InnerPageHeader.Title = model.PageTitle;
            model.InnerPageHeader.Description = CurrentContent.HeadingSummaryText;
            var sources = new List<string>();
            foreach (var source in model.SourceTypes)
            {
                sources.Add(source.SourceName);
            }
            ViewBag.SourceList = sources.Select(f => new SelectListItem() { Value = f, Text = f, });
            if (CurrentContent.Graphic != 0)
            {
                model.InnerPageHeader.Graphic = Mapper.Map<CtaItem>(CurrentContent.Graphic);
            }
            return View(model);
        }
    }
}

0 个答案:

没有答案