[英]Error developing web project + api + SQL Server + dotnet
我必須開發一個訪問 SQL Server 表並在 HTTP-REST 上返回 JSON 的小項目。 我測試了一個直接項目來訪問我的program.cs
直接數據庫並且它有效,但是當我嘗試集成一個基本的 Web API 項目時,我的項目並沒有出現在索引或GET
路由中。
基本配置( appsettings.json
):
"ConnectionStrings": {
"ConnectAppDatabase": "Server=<my_domain>.database.windows.net;Database=<my_base>;user id=<my_user>;password=<my_password>"
}
輪播 ( launchSettings.json
)
..."connect_app": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "connectAppController",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
(啟動.cs)
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<connectAppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectAppDatabase")));
services.AddControllers();
}
在我的控制器中,索引只是一個靜態頁面,在 get 路由中我想返回一個查詢
https://localhost:5001/api/connectapp/getmensage?codigo=<code_example>
namespace Controllers
{
[Route("api/[controller]")]
[ApiController]
public class connectAppController : Controller
{
private readonly connectAppContext _context;
public connectAppController(connectAppContext context)
{
_context = context;
}
public IActionResult Index()
{
Console.Write("Index");
Console.ReadLine();
return View();
}
[HttpGet("{codigo:length(12)}", Name = "getmessage")]
public ActionResult<byte[]> Get(string cod)
{
if (cod == null)
{
return NotFound();
}
var mensage = _context.mensages.FirstOrDefault(m => m.codigo == cod);
if (mensage == null)
{
return NotFound();
}
byte[] jsonUtf8Bytes;
var options = new JsonSerializerOptions
{
WriteIndented = true
};
jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(mensage, options);
return jsonUtf8Bytes;
}
}
}
當我運行該項目時,它不會返回任何錯誤,但是當訪問 url 時,我只會收到默認消息 404 - 找不到頁面
shinier01@shinier01:~/Projetos/Connect-cargo/connect-app$ dotnet run info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001 info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000 info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development info: Microsoft.Hosting.Lifetime[0]
Content root path: /home/shinier01/Projetos/Connect-cargo/connect-app
有誰知道我做錯了什么? 如果是手,我該如何連接 SQL Server 數據庫? 或者我的功能中的一些配置/命令?
更新
從我的調試中可以看出,它在路由https://localhost:5001
上打開網絡瀏覽器,出現錯誤消息,但從未通過Index()
中的斷點
改變
[Route("api/[controller]")]
到
[Route("api")]
然后運行應用程序並調用
https://localhost:5001/api/getmessage?codigo=<cod_exemple>
我能夠至少讓我的頁面訪問路由並出現調試,但現在返回錯誤
invalidOperationException:沒有注冊類型為“Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory”的服務。
我評論了我的控制器
//[Route("api")]
//[ApiController]
並將其添加到我的 Startup.cs 配置
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=connectApp}/{action=Index}/");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.