c# - Asp.net core - 类库上的 Web Api

标签 c# asp.net-core class-library

我正在尝试制作 n 层应用程序,其中 web api 保存在不同的类库中。我在不同的类库中制作了一个 TestController Controller 类,我的代码是这样的

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace PkrUni.SMS.Api
{
    [ApiController]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class TestController : ControllerBase
    {
        public IEnumerable<string> Get()
        {
            return new string[] { "Chris", "Hadfield" };
        }
    }
}

现在我的问题是如何在我的主项目上访问这个 web api。我已经在主项目中添加了对该类库的引用,但它不起作用。我的 api 不工作。 404 Page Not Found 尝试访问 api 时出现错误。 这是我的项目结构。

enter image description here

我做错了什么请帮助我。

最佳答案

尝试在 razor 类库中安装 Microsoft.AspNetCore.Mvc 包。 在 startup.cs 中使用:

services.AddMvc().AddApplicationPart(Assembly.Load(new AssemblyName("PkrUni.SMS.Area.Api")));

引用here .

我通过创建一个 asp.net core2.2 MVC 项目和 razor 类库来测试你的场景,没有任何问题。以下是我的结构:

enter image description here

关于c# - Asp.net core - 类库上的 Web Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55907206/

相关文章:

c++ - 在类库项目 C++ 中创建模板类

c# - 如何在具有单行ListView 的移动屏幕上快速显示附加数据?

c# - 如何使用 Jquery 在下拉列表中填充数据

c# - 多部分/表单数据请求——上传 pdf 导致生成空白文件

.net - 将内部类公开为公共(public)属性

类库中的 Azure Function 引用

c# - 在 ValueSourceAttribute 上指定的 sourceName 必须引用非 null 静态字段、属性或方法

c# - 如何在控制台应用程序中使用 WebView2

c# - 无法将字符串转换为 TimeSpan

c# - 在 core 3.0 中将 View 渲染为字符串 : Could not find an IRouter associated with the ActionContext