简体   繁体   English

运行 .net 核心 web api 项目时出错

[英]Error while running .net core web api project

I am learning .net core web api.我正在学习 .net 核心 web api。 trying to connect with mysql.试图与 mysql 连接。 I am getting error following error我收到错误后的错误

System.InvalidOperationException: Unable to resolve service for type 'WebApplication4.Models.ConnectionStrings' while attempting to activate 'WebApplication4.Controllers.UserController'.
  at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
  at lambda_method9(Closure , IServiceProvider , Object[] )
  at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
  at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
  at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
  at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()

Here's my Startup.cs looks like this这是我的Startup.cs看起来像这样

using Microsoft.AspNetCore.Builder;
using Microsoft.OpenApi.Models;
using WebApplication4.Models;

namespace WebApplication4
{
    public class Startup
    {
        public IConfigurationRoot Configuration { get; }
        public Startup(Microsoft.Extensions.Hosting.IHostingEnvironment env)
        {
            var appsettings = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json")
                .Build();
            Configuration = appsettings;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            ConnectionStrings con = new ConnectionStrings();
            Configuration.Bind("ConnectionStrings", con);
            services.AddSingleton(con);

            services.AddControllers();
            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = ".Net Core 3 Web API", Version = "v1" });
            var filePath = Path.Combine(AppContext.BaseDirectory, "NetCore3WebAPI.xml");
            c.IncludeXmlComments(filePath);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", ".Net Core 3 Web API V1");
            });
        }
    }
}

Usercontroller.cs用户控制器.cs

using Dapper;
using Microsoft.AspNetCore.Mvc;
using MySqlConnector;
using WebApplication4.Models;
using System.Threading.Tasks;

namespace WebApplication4.Controllers
{
    [Route("api/User")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly Models.ConnectionStrings con;
        public UserController(Models.ConnectionStrings c)
        {
            con = c;
        }

        /// <summary>
        /// List users
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] Models.User vm)
        {
            return await Task.Run(() =>
            {
                using (var c = new MySqlConnection(con.MySQL))
                {
                    var sql = @"SELECT * FROM user 
                                WHERE (@id = 0 OR id = @id) 
                                AND (@name IS NULL OR UPPER(name) = UPPER(@name))";
                    var query = c.Query<Models.User>(sql, vm, commandTimeout: 30);
                    return Ok(query);
                }
            });
        }

        /// <summary>
        /// Create user
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] Models.User vm)
        {
            return await Task.Run(() =>
            {
                using (var c = new MySqlConnection(con.MySQL))
                {
                    var sql = @"INSERT INTO user (name) VALUES (@name)";
                    c.Execute(sql, vm, commandTimeout: 30);
                    return Ok();
                }
            });
        }
    }
}

ConnectionStrings.cs连接字符串.cs

namespace WebApplication4.Models
{
    public class ConnectionStrings
    {
        public string MySQL { get; set; }
    }
}

Since the error mentions about UserController and ConnectionString classes, I have added only 2 of them.由于错误提到了UserControllerConnectionString类,我只添加了其中的 2 个。

Let me know how to solve this.让我知道如何解决这个问题。 Thanks谢谢

You are creating a Singleton of a connection string.您正在创建连接字符串的 Singleton。 But then again not injecting it anywhere.但话又说回来,不要在任何地方注射它。 As a result the controller cant find what it is looking for.结果,controller 无法找到它正在寻找的东西。

The better approach to do would be to use the configuration object itself.更好的方法是使用配置 object 本身。 Which can be reused anywhere on the application.可以在应用程序的任何地方重用。 Here is how you can build and inject the configuration in controllers:以下是在控制器中构建和注入配置的方法:

Startup class:启动 class:

public IConfiguration Configuration { get; }

public Startup(IConfiguration configuration, Microsoft.Extensions.Hosting.IHostingEnvironment env)
{
    Configuration = configuration;
}

Controller: Controller:

using Microsoft.Extensions.Configuration;

private IConfiguration _configuration;

public UserController(IConfiguration configuration)
{
    _configuration = configuration;
}

public async Task<IActionResult> Get([FromQuery] Models.User vm)
{
    var connstring= _configuration.GetValue<string>("ConnectionStrings:DefaultConnection");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 运行.NET Core API项目会出现错误502.5-进程失败 - Running .NET Core API project gives Error 502.5 - Process Failure Cors Error 'Access Control Allow Origin' while calling .net core web api from .net core mvc - Cors Error 'Access Control Allow Origin' while calling .net core web api from .net core mvc OR/M 在 .NET Core Web API 项目中可用吗? - Is OR/M available in .NET core web API project? 运行asp.net核心api项目时如何在vscode中设置不打开新的web浏览器选项卡 - How to set not to open new web browser tab in vscode when running asp.net core api project How to add .net core Web API project to an existing .NET core (3.1) Web Application project? - How to add .net core Web API project to an existing .NET core (3.1) Web Application project? .Net Core 3 web api 的自定义错误对象 - Custom error objects for .Net Core 3 web api 在 IIS 上启动 .NET Core Web API 时出错:“应用程序正在 IIS 进程内运行,但未配置为使用 IIS 服务器” - Error on starting .NET Core Web API on IIS: "Application is running inside IIS process but is not configured to use IIS server" 从.net核心WEB API获取500错误以进行长期运行的任务 - Getting 500 error from .net core WEB API for long running task 如何在 .NET 核心 5 Web ZDB974238714CA8DE634A7CE1D083A1 项目中自动格式化 API 响应? - How to autoformat API response in .NET core 5 Web API project? Blazor 添加一个 ASP.NET Core 时出现 Webassembly 错误 Web API 项目参考 - Blazor Webassembly error when adding a ASP.NET Core Web API Project Reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM