gpt4 book ai didi

c# - 异步 MVC Controller 和 HttpTaskAsyncHandler

转载 作者:行者123 更新时间:2023-11-30 23:24:59 27 4
gpt4 key购买 nike

我正在尝试为我的自定义内容管理解决方案实现自定义 HttpTaskAsyncHandler。这个想法是将 /100/my-little-pony 路由到 /Details/my-little-pony。我希望通过以下 HttpTaskAsyncHandler 实现此目的:

public override async Task ProcessRequestAsync(HttpContext context)
{
try
{
var id = GetContentIdFromRouteData();

// Retrieve the content identified by the specified ID
var contentRepository = new ContentRepository();
var content = await contentRepository.GetAsync(id);

if (content == null)
throw new ContentNotFoundException(id);

// Initialize an instance of the content controller
var factory = ControllerBuilder.Current.GetControllerFactory();
var controller = (IContentController) factory.CreateController(_requestContext, content.ControllerName);
if (controller == null)
throw new ControllerNotFoundException(content.ControllerName);

try
{
// Retrieve all content type values and pass them on the the method for index pages
var action = _requestContext.RouteData.GetRequiredString("action");
if (action == "Index")
{
ContentType data = null;
if (controller.ContentType != null)
{
data = BusinessHost.Resolve<ContentType>(controller.ContentType);
data.Values = content.Parameters.ToDictionary(p => p.Name, p => p.Value);
}
_requestContext.RouteData.Values.Add("data", data);
}

var values = _requestContext.RouteData.Values;
values.Add("name", content.Name);
values.Add("controllerId", id);
values.Add("controller", content.ControllerName);

controller.Execute(_requestContext);
}
finally
{
factory.ReleaseController(controller);
}
}
catch (ContentNotFoundException ex)
{
Trace.TraceWarning($"404: {ex.Message}");
_requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
}
}

这对于同步请求非常有效,但是当我尝试调用异步方法时......

@using (Html.BeginForm("Save", Html.ControllerId(), FormMethod.Post, new { @class = "form-horizontal" }))

...这就是方法...

[HttpPost]
public async Task<ActionResult> Save(NewsViewModel model)
{ }

编辑 我已将方法名称更改为保存,因为未推断异步,我收到一个新错误:

The asynchronous action method 'Login' returns a Task, which cannot be executed synchronously.

最佳答案

操作名称是 SaveAsync,但引用它的代码使用 Save 作为名称。任何操作都没有神奇的重命名,包括异步一次。

您的选择:

  • 使用 SaveAsync 来引用操作
  • 使用ActionName attribute重命名 Action
  • 将方法重命名为Save(但这违反了所有async 方法都具有...Async 后缀的约定)

旁注:与某些自定义处理程序相比,使用路由可能是重定向的更好选择。

关于c# - 异步 MVC Controller 和 HttpTaskAsyncHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37501913/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com