AspNetCore源码之WebHost.cs类

本文深入解析了ASP.NET Core中WebHost类的源码,详细介绍了WebHost的初始化、启动和服务提供者创建过程。同时,文章探讨了WebHost如何处理异常、配置服务器地址以及与依赖注入、生命周期管理等关键组件的交互。

Microsoft.AspNetCore.Hosting.Internal命名空间

WebHost.cs源码

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Hosting.Views;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.StackTrace.Sources;
 
namespace Microsoft.AspNetCore.Hosting.Internal
{
    internal class WebHost : IWebHost, IAsyncDisposable
    {
        private static readonly string DeprecatedServerUrlsKey = "server.urls";
 
        private readonly IServiceCollection _applicationServiceCollection;
        private IStartup _startup;
        private ApplicationLifetime _applicationLifetime;
        private HostedServiceExecutor _hostedServiceExecutor;
 
        private readonly IServiceProvider _hostingServiceProvider;
        private readonly WebHostOptions _options;
        private readonly IConfiguration _config;
        private readonly AggregateException _hostingStartupErrors;
 
        private IServiceProvider _applicationServices;
        private ExceptionDispatchInfo _applicationServicesException;
        private ILogger<WebHost> _logger;
 
        private bool _stopped;
 
        // Used for testing only
        internal WebHostOptions Options => _options;
 
        private IServer Server { get; set; }
 
        public WebHost(
            IServiceCollection appServices,
            IServiceProvider hostingServiceProvider,
            WebHostOptions options,
            IConfiguration config,
            AggregateException hostingStartupErrors)
        {
            if (appServices == null)
            {
                throw new ArgumentNullException(nameof(appServices));
            }
 
            if (hostingServiceProvider == null)
            {
                throw new ArgumentNullException(nameof(hostingServiceProvider));
            }
 
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }
 
            _config = config;
            _hostingStartupErrors = hostingStartupErrors;
            _options = options;
            _applicationServiceCollection = appServices;
            _hostingServiceProvider = hostingServiceProvider;
            _applicationServiceCollection.AddSingleton<IApplicationLifetime, ApplicationLifetime>();
            // There's no way to to register multiple service types per definition. See https://github.com/aspnet/DependencyInjection/issues/360
            _applicationServiceCollection.AddSingleton(sp =>
            {
                return sp.GetRequiredService<IApplicationLifetime>() as Extensions.Hosting.IApplicationLifetime;
            });
            _applicationServiceCollection.AddSingleton<HostedServiceExecutor>();
        }
 
        public IServiceProvider Services
        {
            get
            {
                return _applicationServices;
            }
        }
 
        public IFeatureCollection ServerFeatures
        {
            get
            {
                EnsureServer();
                return Server?.Features;
            }
        }
 
        // Called immediately after the constructor so the properties can rely on it.
        public void Initialize()
        {
            try
            {
                EnsureApplicationServices();
            }
            catch (Exception ex)
            {
                // EnsureApplicationServices may have failed due to a missing or throwing Startup class.
                if (_applicationServices == null)
                {
                    _applicationServices = _applicationServiceCollection.BuildServiceProvider();
                }
 
                if (!_options.CaptureStartupErrors)
                {
                    throw;
                }
 
                _applicationServicesException = ExceptionDispatchInfo.Capture(ex);
            }
        }
 
        public void Start()
        {
            StartAsync().GetAwaiter().GetResult();
        }
 
        public virtual async Task StartAsync(CancellationToken cancellationToken = default)
        {
            HostingEventSource.Log.HostStart();
            _logger = _applicationServices.GetRequiredService<ILogger<WebHost>>();
            _logger.Starting();
 
            var application = BuildApplication();
 
            _applicationLifetime = _applicationServices.GetRequiredService<IApplicationLifetime>() as ApplicationLifetime;
            _hostedServiceExecutor = _applicationServices.GetRequiredService<HostedServiceExecutor>();
            var diagnosticSource = _applicationServices.GetRequiredService<DiagnosticListener>();
            var httpContextFactory = _applicationServices.GetRequiredService<IHttpContextFactory>();
            var hostingApp = new HostingApplication(application, _logger, diagnosticSource, httpContextFactory);
            await Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(false);
 
            // Fire IApplicationLifetime.Started
            _applicationLifetime?.NotifyStarted();
 
            // Fire IHostedService.Start
            await _hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(false);
 
            _logger.Started();
 
            // Log the fact that we did load hosting startup assemblies.
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                foreach (var assembly in _options.GetFinalHostingStartupAssemblies())
                {
                    _logger.LogDebug("Loaded hosting startup assembly {assemblyName}", assembly);
                }
            }
 
            if (_hostingStartupErrors != null)
            {
                foreach (var exception in _hostingStartupErrors.InnerExceptions)
                {
                    _logger.HostingStartupAssemblyError(exception);
                }
            }
        }
 
        private void EnsureApplicationServices()
        {
            if (_applicationServices == null)
            {
                EnsureStartup();
                _applicationServices = _startup.ConfigureServices(_applicationServiceCollection);
            }
        }
 
        private void EnsureStartup()
        {
            if (_startup != null)
            {
                return;
            }
 
            _startup = _hostingServiceProvider.GetService<IStartup>();
 
            if (_startup == null)
            {
                throw new InvalidOperationException($"No application configured. Please specify startup via IWebHostBuilder.UseStartup, IWebHostBuilder.Configure, injecting {nameof(IStartup)} or specifying the startup assembly via {nameof(WebHostDefaults.StartupAssemblyKey)} in the web host configuration.");
            }
        }
 
        private RequestDelegate BuildApplication()
        {
            try
            {
                _applicationServicesException?.Throw();
                EnsureServer();
 
                var builderFactory = _applicationServices.GetRequiredService<IApplicationBuilderFactory>();
                var builder = builderFactory.CreateBuilder(Server.Features);
                builder.ApplicationServices = _applicationServices;
 
                var startupFilters = _applicationServices.GetService<IEnumerable<IStartupFilter>>();
                Action<IApplicationBuilder> configure = _startup.Configure;
                foreach (var filter in startupFilters.Reverse())
                {
                    configure = filter.Configure(configure);
                }
 
                configure(builder);
 
                return builder.Build();
            }
            catch (Exception ex)
            {
                if (!_options.SuppressStatusMessages)
                {
                    // Write errors to standard out so they can be retrieved when not in development mode.
                    Console.WriteLine("Application startup exception: " + ex.ToString());
                }
                var logger = _applicationServices.GetRequiredService<ILogger<WebHost>>();
                logger.ApplicationError(ex);
 
                if (!_options.CaptureStartupErrors)
                {
                    throw;
                }
 
                EnsureServer();
 
                // Generate an HTML error page.
                var hostingEnv = _applicationServices.GetRequiredService<IHostingEnvironment>();
                var showDetailedErrors = hostingEnv.IsDevelopment() || _options.DetailedErrors;
 
                var model = new ErrorPageModel
                {
                    RuntimeDisplayName = RuntimeInformation.FrameworkDescription
                };
                var systemRuntimeAssembly = typeof(System.ComponentModel.DefaultValueAttribute).GetTypeInfo().Assembly;
                var assemblyVersion = new AssemblyName(systemRuntimeAssembly.FullName).Version.ToString();
                var clrVersion = assemblyVersion;
                model.RuntimeArchitecture = RuntimeInformation.ProcessArchitecture.ToString();
                var currentAssembly = typeof(ErrorPage).GetTypeInfo().Assembly;
                model.CurrentAssemblyVesion = currentAssembly
                    .GetCustomAttribute<AssemblyInformationalVersionAttribute>()
                    .InformationalVersion;
                model.ClrVersion = clrVersion;
                model.OperatingSystemDescription = RuntimeInformation.OSDescription;
 
                if (showDetailedErrors)
                {
                    var exceptionDetailProvider = new ExceptionDetailsProvider(
                        hostingEnv.ContentRootFileProvider,
                        sourceCodeLineCount: 6);
 
                    model.ErrorDetails = exceptionDetailProvider.GetDetails(ex);
                }
                else
                {
                    model.ErrorDetails = new ExceptionDetails[0];
                }
 
                var errorPage = new ErrorPage(model);
                return context =>
                {
                    context.Response.StatusCode = 500;
                    context.Response.Headers["Cache-Control"] = "no-cache";
                    return errorPage.ExecuteAsync(context);
                };
            }
        }
 
        private void EnsureServer()
        {
            if (Server == null)
            {
                Server = _applicationServices.GetRequiredService<IServer>();
 
                var serverAddressesFeature = Server.Features?.Get<IServerAddressesFeature>();
                var addresses = serverAddressesFeature?.Addresses;
                if (addresses != null && !addresses.IsReadOnly && addresses.Count == 0)
                {
                    var urls = _config[WebHostDefaults.ServerUrlsKey] ?? _config[DeprecatedServerUrlsKey];
                    if (!string.IsNullOrEmpty(urls))
                    {
                        serverAddressesFeature.PreferHostingUrls = WebHostUtilities.ParseBool(_config, WebHostDefaults.PreferHostingUrlsKey);
 
                        foreach (var value in urls.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            addresses.Add(value);
                        }
                    }
                }
            }
        }
 
        public async Task StopAsync(CancellationToken cancellationToken = default)
        {
            if (_stopped)
            {
                return;
            }
            _stopped = true;
 
            _logger?.Shutdown();
 
            var timeoutToken = new CancellationTokenSource(Options.ShutdownTimeout).Token;
            if (!cancellationToken.CanBeCanceled)
            {
                cancellationToken = timeoutToken;
            }
            else
            {
                cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutToken).Token;
            }
 
            // Fire IApplicationLifetime.Stopping
            _applicationLifetime?.StopApplication();
 
            if (Server != null)
            {
                await Server.StopAsync(cancellationToken).ConfigureAwait(false);
            }
 
            // Fire the IHostedService.Stop
            if (_hostedServiceExecutor != null)
            {
                await _hostedServiceExecutor.StopAsync(cancellationToken).ConfigureAwait(false);
            }
 
            // Fire IApplicationLifetime.Stopped
            _applicationLifetime?.NotifyStopped();
 
            HostingEventSource.Log.HostStop();
        }
 
        public void Dispose()
        {
            DisposeAsync().ConfigureAwait(false).GetAwaiter().GetResult();
        }
 
        public async ValueTask DisposeAsync()
        {
            if (!_stopped)
            {
                try
                {
                    await StopAsync().ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _logger?.ServerShutdownException(ex);
                }
            }
 
            await DisposeServiceProviderAsync(_applicationServices).ConfigureAwait(false);
            await DisposeServiceProviderAsync(_hostingServiceProvider).ConfigureAwait(false);
        }
 
        private async ValueTask DisposeServiceProviderAsync(IServiceProvider serviceProvider)
        {
            switch (serviceProvider)
            {
                case IAsyncDisposable asyncDisposable:
                    await asyncDisposable.DisposeAsync();
                    break;
                case IDisposable disposable:
                    disposable.Dispose();
                    break;
            }
        }
    }
}
INFO 2025-07-23 15:24:56,497 [161 ] soft.AspNetCore.Hosting.Internal.WebHost - Request starting HTTP/1.0 POST http://13.85.254.9:8166/api/services/app/DataImportService/ImportDataFileAsync multipart/form-data; boundary=----WebKitFormBoundaryJB846y1an0UYVNYV 12811 INFO 2025-07-23 15:24:56,498 [161 ] pNetCore.Cors.Infrastructure.CorsService - Policy execution failed. INFO 2025-07-23 15:24:56,498 [161 ] pNetCore.Cors.Infrastructure.CorsService - Request origin http://localhost:8090 does not have permission to access the resource. INFO 2025-07-23 15:24:56,498 [161 ] uthentication.JwtBearer.JwtBearerHandler - Successfully validated the token. INFO 2025-07-23 15:24:56,502 [ion:0] ore.Mvc.Internal.ControllerActionInvoker - Route matched with {area = "app", action = "ImportDataFileAsync", controller = "DataImportService"}. Executing action Zebra.Data.DataImportService.ImportDataFileAsync (Zebra.Application) INFO 2025-07-23 15:24:56,502 [ion:0] pNetCore.Cors.Infrastructure.CorsService - Policy execution failed. INFO 2025-07-23 15:24:56,502 [ion:0] pNetCore.Cors.Infrastructure.CorsService - Request origin http://localhost:8090 does not have permission to access the resource. INFO 2025-07-23 15:24:56,503 [ion:0] uthorization.DefaultAuthorizationService - Authorization was successful. INFO 2025-07-23 15:24:56,503 [ion:0] Abp.Logging.LogHelper - The Root Path:D:\Suncere\Web服务\pub-exe INFO 2025-07-23 15:24:56,503 [ion:0] Abp.Logging.LogHelper - NOT DEBUG INFO 2025-07-23 15:24:56,505 [ion:0] ore.Mvc.Internal.ControllerActionInvoker - Executing action method Zebra.Data.DataImportService.ImportDataFileAsync (Zebra.Application) with arguments (Microsoft.AspNetCore.Http.Internal.FormFile) - Validation state: Valid ERROR 2025-07-23 15:24:56,514 [161 ] Zebra.Web.Core.Mvc.ZebraExceptionFilter - Sheet index (1) is out of range (0..0) System.ArgumentException: Sheet index (1) is out of range (0..0) at Zebra.Data.DataImportService.ImportDataFileAsync(IFormFile file) in F:\海南\HaiNanSystem\【XC-201901148】海南省环境空气质量联网建设项目\源码\Trunk\城市平台(源于新框架84121)\src\Zebra.Application\Data\DataImportService.cs:line 363 at lambda_method(Closure , Object ) at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync() INFO 2025-07-23 15:24:56,518 [161 ] .Mvc.Infrastructure.ObjectResultExecutor - Executing ObjectResult, writing value of type 'Abp.Web.Models.AjaxResponse'. INFO 2025-07-23 15:24:56,518 [161 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action Zebra.Data.DataImportService.ImportDataFileAsync (Zebra.Application) in 15.962ms INFO 2025-07-23 15:24:56,518 [161 ] soft.AspNetCore.Hosting.Internal.WebHost - Request finished in 21.0612ms 500 application/json; charset=utf-8 导入失败,分析报错
07-24
引发的异常:“System.InvalidOperationException”(位于 System.Private.CoreLib.dll 中) 引发的异常:“System.InvalidOperationException”(位于 System.Private.CoreLib.dll 中) 引发的异常:“System.InvalidOperationException”(位于 System.Private.CoreLib.dll 中) 引发的异常:“System.InvalidOperationException”(位于 System.Private.CoreLib.dll 中) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request. System.InvalidOperationException: The view 'Index' was not found. The following locations were searched: /Views/PayMain/Index.cshtml /Views/Shared/Index.cshtml at Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable`1 originalLocations) at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result) at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) 线程 28460 已退出,返回值为 0 (0x0)。
最新发布
08-20
<think>我们正在处理的问题是在Web API项目中,尝试返回视图时遇到异常:`System.InvalidOperationException: The view 'Index' was not found`。根据之前的讨论,我们知道Web API默认不支持视图,但通过继承`Controller`(而不是`ControllerBase`)并正确配置,可以返回视图。然而,现在出现了视图找不到的异常,我们需要分析原因并提供解决方案。 ### 问题分析 1. **视图查找机制**:ASP.NET Core MVC按照以下路径查找视图: - `/Views/{控制器名}/{视图名}.cshtml` - `/Views/Shared/{视图名}.cshtml` 2. **常见原因**: - 视图文件未放置在正确的位置 - 视图文件名与在控制器中指定的视图名不匹配 - 未正确配置视图服务(例如,未调用`AddControllersWithViews`) ### 解决方案 #### 1. 确认视图文件位置和命名 假设控制器名为`HomeController`,方法返回`View("Index")`,则视图文件应位于: - `/Views/Home/Index.cshtml` 或者共享视图: - `/Views/Shared/Index.cshtml` **检查点**: - 确保视图文件存在且命名正确(包括大小写,在Linux环境下大小写敏感) - 确保视图文件扩展名为`.cshtml` #### 2. 配置视图服务 在`Program.cs`(或`Startup.cs`)中,必须添加对视图的支持: ```csharp // Program.cs builder.Services.AddControllersWithViews(); // 关键:启用视图支持 ``` #### 3. 配置路由 确保在应用程序构建器中正确配置了MVC路由: ```csharp app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); ``` #### 4. 控制器继承自`Controller` 确保控制器继承自`Controller`(而不是`ControllerBase`): ```csharp public class HomeController : Controller // 正确继承 { public IActionResult Index() { return View(); } } ``` #### 5. 处理视图路径问题 如果视图位于非标准路径,可以指定完整路径(绝对路径): ```csharp public IActionResult Index() { return View("~/Views/MyCustomFolder/Index.cshtml"); } ``` ### 错误示例分析 假设我们有以下代码: ```csharp [ApiController] [Route("api/[controller]")] public class ViewApiController : Controller // 继承自Controller { [HttpGet] public IActionResult GetView() { return View("Index"); // 试图返回名为"Index"的视图 } } ``` 如果出现`The view 'Index' was not found`,请按以下步骤检查: 1. 视图文件是否存在?检查路径:`/Views/ViewApi/Index.cshtml`(注意控制器名是`ViewApi`,去掉`Controller`后缀) 2. 如果不存在,检查共享视图目录:`/Views/Shared/Index.cshtml` 3. 如果都没有,则创建视图文件。 ### 补充:视图查找规则详解 - **控制器专属视图**:`/Views/<控制器名>/<视图名>.cshtml` - 控制器名:去除`Controller`后缀的控制器名(例如`HomeController` -> `Home`) - **共享视图**:`/Views/Shared/<视图名>.cshtml` - **区域视图**:`/Areas/<区域名>/Views/<控制器名>/<视图名>.cshtml`(如果使用区域) ### 验证步骤 1. 在项目中创建正确的视图目录结构 2. 在视图中添加简单内容(如`<h1>Hello World</h1>`) 3. 运行并访问对应路由 ### 示例项目结构 ``` 项目根目录 │ ├── Controllers │ └── HomeController.cs │ ├── Views │ ├── Home │ │ └── Index.cshtml │ └── Shared │ └── Error.cshtml │ └── Program.cs ``` ### 高级场景:自定义视图位置 如果需要自定义视图查找路径,可以实现`IViewLocationExpander`: ```csharp public class CustomViewLocationExpander : IViewLocationExpander { public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { // 添加自定义路径 return new[] { "/MyCustomViews/{1}/{0}.cshtml", // {1}为控制器名,{0}为视图名 "/MyCustomViews/Shared/{0}.cshtml" }.Concat(viewLocations); } public void PopulateValues(ViewLocationExpanderContext context) { } } ``` 在`Program.cs`中注册: ```csharp builder.Services.Configure<MvcOptions>(options => { options.ViewLocationExpanders.Add(new CustomViewLocationExpander()); }); ``` ### 性能优化 - **预编译视图**:在发布时预编译视图以提高首次加载速度 ```xml <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish> </PropertyGroup> ``` ### 常见错误排查表 | 错误现象 | 可能原因 | 解决方案 | |----------|----------|----------| | 视图未找到 | 视图文件位置错误 | 检查文件路径和命名 | | 视图未找到 | 未启用视图服务 | 调用`AddControllersWithViews` | | 视图未找到 | 控制器未继承`Controller` | 修改控制器继承 | | 视图渲染错误 | 视图语法错误 | 检查视图中的Razor语法 | ### 总结 当在Web API中遇到`The view 'Index' was not found`异常时,核心解决步骤: 1. **确认视图存在**:检查标准视图路径 2. **启用视图服务**:在`Program.cs`中调用`AddControllersWithViews` 3. **正确继承**:控制器继承`Controller`基 4. **配置路由**:使用`MapControllerRoute`映射MVC路由 > 注意:在Web API项目中返回视图通常不是最佳实践,因为它混合了API和UI的职责。但在某些场景下(如服务端渲染部分页面),这种方案是可行的[^1][^2]。 §§相关问题§§ 1. 如何在ASP.NET Core中自定义视图的查找路径? 2. 在Web API项目中返回视图有哪些性能影响? 3. 如何为Web API返回的视图添加布局(Layout)? 4. 在Razor视图中如何使用依赖注入? 5. 如何为Web API项目中的视图配置全局过滤器?</think>### 解决 Web API 中视图找不到的异常(`System.InvalidOperationException: The view 'Index' was not found`) 在 Web API 项目中遇到视图找不到的异常,通常是因为 Web API 默认不包含视图渲染能力。以下是完整解决方案,结合引用内容分析核心问题: --- ### 问题根本原因分析 1. **继承关系错误** Web API 控制器默认继承 `ControllerBase`(无视图能力),而非 `Controller`(支持视图)[^1] ```csharp // 错误:无法返回视图 public class MyController : ControllerBase // 正确:支持视图 public class MyController : Controller ``` 2. **视图服务未启用** Web API 默认不加载视图引擎(缺少 `AddControllersWithViews()` 注册)[^1] 3. **视图路径错误** ASP.NET Core 严格遵循视图查找规则: ``` /Views/{ControllerName}/{ViewName}.cshtml /Views/Shared/{ViewName}.cshtml ``` --- ### 完整解决方案 #### 步骤 1:修改控制器继承关系 ```csharp // 修改前(默认API控制器) [ApiController] [Route("api/[controller]")] public class MyController : ControllerBase // ❌ 无法使用View() // 修改后 [ApiController] [Route("api/[controller]")] public class MyController : Controller // ✅ 继承Controller而非ControllerBase { [HttpGet] public IActionResult Get() { return View("Index"); // 现在可使用View() } } ``` #### 步骤 2:启用视图服务(Program.cs) ```csharp var builder = WebApplication.CreateBuilder(args); // 添加以下服务注册 builder.Services.AddControllersWithViews(); // ✅ 关键:启用视图引擎[^1] var app = builder.Build(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); // 映射API控制器 }); ``` #### 步骤 3:创建正确的视图结构 ``` 项目根目录 ├── Views │ ├── My // 控制器名(去掉Controller后缀) │ │ └── Index.cshtml // 视图文件 │ └── Shared // 共享视图目录 │ └── _Layout.cshtml ``` #### 步骤 4:处理循环引用问题(如引用[4]) 若视图涉及EF Core实体序列化,添加以下配置: ```csharp // Program.cs builder.Services.AddControllersWithViews() .AddJsonOptions(options => { options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve; // 解决循环引用[^4] }); ``` --- ### 错误排查清单 | 错误现象 | 解决方案 | |----------|----------| | `The view 'Index' was not found` | 检查视图路径是否为 `/Views/My/Index.cshtml` | | `System.Web.Http.WebHost` 加载失败 | 确保项目型为 ASP.NET Core(非旧版ASP.NET)[^1] | | JSON序列化循环引用 | 配置 `ReferenceHandler.Preserve` [^4] | | 内容长度不匹配 | 检查视图是否包含动态内容导致长度计算错误[^3] | --- ### 备选方案:直接返回HTML 若不想继承 `Controller`,可返回HTML内容: ```csharp [HttpGet("html")] public ContentResult GetHtml() { return new ContentResult { ContentType = "text/html", Content = "<html><body><h1>直接返回HTML</h1></body></html>" }; } ``` ### 性能优化建议 1. **预编译视图**(发布时) ```xml <!-- .csproj 文件 --> <PropertyGroup> <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish> </PropertyGroup> ``` 2. **部分视图加载** ```csharp // 返回轻量级部分视图 public IActionResult GetWidget() => PartialView("_Widget"); ``` > **关键原则**:Web API 设计上应返回数据而非视图。返回视图需明确业务需求,并注意混合架构的维护成本[^1][^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值