gpt4 book ai didi

c# - 将 View 呈现为字符串 : ArgumentOutOfRangeException

转载 作者:行者123 更新时间:2023-11-30 14:47:35 25 4
gpt4 key购买 nike

我有一个 asp.net 核心应用程序,我有一个名为 ViewRenderService 的服务,它可以将 View 转换为字符串,以便我根据发出的请求呈现某些 View 。

ViewRenderService:

public class ViewRenderService : IViewRenderService
{
private readonly IRazorViewEngine _razorViewEngine;
private readonly ITempDataProvider _tempDataProvider;
private readonly IServiceProvider _serviceProvider;

public ViewRenderService(IRazorViewEngine razorViewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider)
{
_razorViewEngine = razorViewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
}

public async Task<string> RenderToStringAsync(string viewName, object model)
{
var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

using (var sw = new StringWriter())
{
var viewResult = _razorViewEngine.GetView(viewName, viewName, false);

if (viewResult.View == null)
{
throw new ArgumentNullException($"{viewName} does not match any available view");
}

var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = model
};

var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewDictionary,
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
sw,
new HtmlHelperOptions()
);

await viewResult.View.RenderAsync(viewContext);
return sw.GetStringBuilder().ToString();
}
}
}

行:

await viewResult.View.RenderAsync

抛出

"System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"

在某些模型/ View 上

它抛出异常的 View 和模型:

验证代码 View 模型:

public class VerifyCodeViewModel
{
[Required (ErrorMessage = "Please enter verification code that was sent via email")]
public string Code { get; set; }
public string ReturnUrl { get; set; }
}

验证.cshtml

@model VerifyCodeViewModel


<div class="row">
<div class="col s12 m5 l5 push-m3 push-l3 center">
<div class="center">
<br />
<form method="post" asp-action="Verify">
<div class="card">
<div class="card-content">
<div class="red-text text-bold" asp-validation-summary="ModelOnly"></div>
<div class="row">
<div class="col 12 m12 l12">
<h4 class="text-bold header caption-uppercase">Verification Token Required</h4>
</div>
</div>
<div class="row">
<div class="col s12 m12 l12">
<p class="center-align">
An email that contains a token have been sent to you. Please enter token below.
</p>
</div>
</div>
<div class="row">
<div class="input-field col 12 m12 l12">
<i class="mdi-communication-vpn-key prefix"></i>
<input type="text" asp-for="Code" placeholder="Enter token here"/>
<span asp-validation-for="Code"></span>
<span class="text-bold red-text">@ViewBag.Message</span>
</div>
</div>
</div>
<div class="card-action">
<button type="submit" class="btn btn-danger">Verify</button>
</div>
</div>
</form>
</div>
</div>
</div>

@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}

请指导我我缺少什么,因为它确实适用于某些 View ,但不适用于上面的 View 。

最佳答案

我遇到了同样的问题,并通过检查我的调用堆栈找到了答案。我这边的问题是:

at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) 
at System.Collections.Generic.List`1.get_Item(Int32 index)
at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.get_Router()
at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.GetVirtualPathData(String routeName, RouteValueDictionary values)
at Microsoft.AspNetCore.Mvc.Routing.UrlHelper.Action(UrlActionContext actionContext)

所以路由器丢失了,通过将代码更改为以下内容解决了这个问题:

public class ViewRenderService : IViewRenderService
{
private readonly IRazorViewEngine _razorViewEngine;
private readonly ITempDataProvider _tempDataProvider;
private readonly IServiceProvider _serviceProvider;
private readonly HttpContext _context;

public ViewRenderService(IRazorViewEngine razorViewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider,
IHttpContextAccessor accessor)
{
_razorViewEngine = razorViewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
_context = accessor.HttpContext;
}

public async Task<string> RenderToStringAsync(string viewName, object model)
{
var actionContext = new ActionContext(_context, new RouteData(), new ActionDescriptor());

using (var sw = new StringWriter())
{
var viewResult = _razorViewEngine.GetView(viewName, viewName, false);

if (viewResult.View == null)
{
throw new ArgumentNullException($"{viewName} does not match any available view");
}

var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
{
Model = model
};

var viewContext = new ViewContext(
actionContext,
viewResult.View,
viewDictionary,
new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
sw,
new HtmlHelperOptions()
);
viewContext.RouteData = _context.GetRouteData();

await viewResult.View.RenderAsync(viewContext);
return sw.GetStringBuilder().ToString();
}
}
}

真正有用的是将上下文从新的 ActionContext 更改为注入(inject)的上下文。通过更改此设置然后设置 RouteData,问题得到解决。

        viewContext.RouteData = _context.GetRouteData();

关于c# - 将 View 呈现为字符串 : ArgumentOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44443659/

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