【问题标题】:Web API error on localhost本地主机上的 Web API 错误
【发布时间】:2017-08-18 20:11:23
【问题描述】:

我开始使用 ASP.NET Core MVC 开发 Web API。我一直在关注这个微软教程:https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api

到目前为止,我已经为以下操作创建了代码:

  • GET /api/todo
  • GET /api/todo/{id}

代码:

[Route("api/[controller]")]
public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;

    public TodoController(ITodoRepository todoRepository)
    {
        _todoRepository = todoRepository;
    }

    // GET: api/values
    [HttpGet]
    public IEnumerable<TodoItem> GetAll()
    {
        return _todoRepository.GetAll();
    }

    // GET api/values/5
    [HttpGet("{id}", Name ="GetTodo")]
    public IActionResult GetById(long id)
    {
        var item = _todoRepository.Find(id);

        if(item == null)
        {
            return NotFound();
        }

        return new ObjectResult(item);
    }
}

但是,当我运行应用程序时,我收到以下 500 错误:

我理解错误的含义,但不知道它发生的原因。我错过了什么吗?

有趣的是,我可以访问在创建应用程序时自动生成的 API。但不是我手动添加的新的。

【问题讨论】:

标签: asp.net-web-api asp.net-web-api2 asp.net-core-mvc asp.net-core-webapi


【解决方案1】:

更改属性中的设置 -> launchSettings.json 文件。

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:49885",
      "sslPort": 44337
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/todo",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "TodoApi": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/todo",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

因为默认情况下“lauchUrl”设置为“api/values”,这就是您收到该错误的原因。 还要在你的 Todo 控制器中添加它,请参阅文档了解为什么应该添加它。

namespace TodoApi.Controllers
{
    [Route("api/todo")]
    [ApiController]

我建议您遵循创建应用程序的指南直到最后并在完成后运行它以避免错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 2019-02-05
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    相关资源
    最近更新 更多