簡體   English   中英

運行 .net 核心 web api 項目時出錯

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

我正在學習 .net 核心 web api。 試圖與 mysql 連接。 我收到錯誤后的錯誤

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()

這是我的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");
            });
        }
    }
}

用戶控制器.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();
                }
            });
        }
    }
}

連接字符串.cs

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

由於錯誤提到了UserControllerConnectionString類,我只添加了其中的 2 個。

讓我知道如何解決這個問題。 謝謝

您正在創建連接字符串的 Singleton。 但話又說回來,不要在任何地方注射它。 結果,controller 無法找到它正在尋找的東西。

更好的方法是使用配置 object 本身。 可以在應用程序的任何地方重用。 以下是在控制器中構建和注入配置的方法:

啟動 class:

public IConfiguration Configuration { get; }

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

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM