[英]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.由于错误提到了
UserController
和ConnectionString
类,我只添加了其中的 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.