如何使用ASP.NET Core API与Microsoft SQL Server连接

时间:2019-05-08 09:54:56

标签: c# asp.net-core asp.net-core-mvc

我对ASP.NET完全陌生。我想创建小的API。我试图将该API与Microsoft Sql Server连接。但它给出的错误是

  

InvalidOperationException:无法找到所需的服务。请通过在应用程序启动代码中对“ ConfigureServices(...)”的调用内调用“ IServiceCollection.AddMvc”来添加所有必需的服务

我的Startup.cs文件是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
//using EFGetStarted.AspNetCore.ExistingDb.Models;
using Microsoft.EntityFrameworkCore;
using myApp.Models;

namespace myApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = @"Server=(JKCS-AREBY\SQLEXPRESS)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
            services.AddDbContext<TodoContext>(options => options.UseSqlServer(connection));
        }

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

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

该错误在app.UseMvc();中指示。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

services.AddDbContext之后... 只需添加services.AddMvc() (就像Msg提示的错误一样)

    public void ConfigureServices(IServiceCollection services)
        {
            var connection = @"Server=(JKCS-AREBY\SQLEXPRESS)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
            services.AddDbContext<TodoContext>(options => options.UseSqlServer(connection));
 services.AddMvc()
        }