【问题标题】:ASP.NET can not find API controllerASP.NET 找不到 API 控制器
【发布时间】:2021-11-18 02:50:23
【问题描述】:

我目前正在开发一个需要从 API 控制器获取字符串的网站,以便它可以将其作为图像显示在页面上。当我在 Visual Studio 中运行该站点时一切正常,但是当我将它发布到网站本身时,服务器总是响应以下内容:

<Error>
<Message>No HTTP resource was found that matches the request URI 'https://{website_name}/api/Files/GetProfilePicture?userId=cc6afd64-885e-4d8b-a239-42b161d665cc'.</Message>
<MessageDetail>No type was found that matches the controller named 'Files'.</MessageDetail>
</Error>

网站中的其他 Api 控制器工作正常,但特别是这个控制器很顽固。

这里是 WebApiConfig.cs:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

这里是视图:

@model {website_name}.Models.ProfilePictureGetModel

@{
    if (Model.userId == null)
    {
        Model.userId = Microsoft.AspNet.Identity.IdentityExtensions.GetUserId(User.Identity);
    }

    string style = "border-radius: " + Model.size + "px; height: " + Model.size + "px; width: " + Model.size + "px; object-fit: cover; cursor: pointer";
}

<body>
    <img class="pflPic @Model.userId" style="@style" onclick="location.href = '/Profile?id=' + '@Model.userId'" />
    @Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
        $.ajax({
            url: "/api/Files/GetProfilePicture",
            data: {
                id: '@Model.userId'
            },
            type: "GET",
            cache: true,
            async: true,
            success: function (result) {
                if (result) {
                    var pics = document.getElementsByClassName("@Model.userId")
                    for (var i = 0; i < pics.length; i++) {
                        if (pics[i].src == "")
                            pics[i].src = result;
                    }
                }
            }
        });
</script>
</body>

这里是控制器:

namespace {website_name}.Controllers.Api
{
    public class FilesController : ApiController
    {
        ApplicationDbContext _context;

        [HttpGet]
        [WebMethod]
        [ResponseType(typeof(String))]
        public IHttpActionResult GetProfilePicture(string userId)
        {
            var User = _context.Users.FirstOrDefault(x => x.Id == userId);

            if (User == null)
                return NotFound();

            string img = Convert.ToBase64String(User.ProfilePicture);
            if (User != null)
                return Ok("data:image;base64," + img);
            else
                return NotFound();
        }

        protected override void Dispose(bool disposing)
        {
            _context.Dispose();
            base.Dispose(disposing);
        }

        public FilesController()
        {
            _context = new ApplicationDbContext();
        }
    }
}

【问题讨论】:

  • 尝试删除 [WebMethod]
  • 我去掉了,没有效果

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


【解决方案1】:

你可以尝试经典的 MVC 风格的 url,如果你的 webapi 不在你的 web 应用程序中,则使用完整的 url

var userId=$('#userId').val();

    $.ajax({
          url: "https://{website_name}/api/Files/GetProfilePicture/"+userId,
            type: "GET",
            success: function (result) {
          ......

并将其添加到您的 Web 应用程序的视图表单中的某个位置

<input id="userId" type="hidden" value="@Model.UserId">

它应该向这个 url 发送请求

https://{website_name}/api/Files/GetProfilePicture/cc6afd64-885e-4d8b-a239-42b161d665cc

动作

[Route("~/api/Files/GetProfilePicture/{userId?}")]
public IHttpActionResult GetProfilePicture(string userId)

【讨论】:

  • 它仍然给了我同样的 404 响应。我认为问题可能是它找不到控制器,但我不知道为什么会这样。
  • @Deathtraptaco 你在 404 响应中看到了什么 url?
  • https://{website_name}/api/Files/GetProfilePicture?userId=cc6afd64-885e-4d8b-a239-42b161d665cc
  • 你使用了我的 ajax 吗?你应该有 https://{website_name}/api/Files/GetProfilePicture/cc6afd64-885e-4d8b-a239-42b161d665cc url 如果你不想按照答案,你不应该在这里问问题。
  • 我添加了您建议的所有更改,现在它重定向到 https://{website_name}/api/Files/GetProfilePicture/cc6afd64-885e-4d8b-a239-42b161d665cc?_=1632622493698。它给了我默认的 404 页面。
【解决方案2】:

您在 ajax 调用中格式化请求 url 的方式存在问题

   url: "/api/Files/GetProfilePicture/" + userId,

应该是的

   url: "/api/Files/GetProfilePicture?" + userId,

【讨论】:

  • 它仍然将我重定向到相同的响应。我不认为这是操作本身的问题,但 asp.net 出于某种原因找不到“文件”控制器。
【解决方案3】:

首先 - 关于 URL:

对于初学者 - 尝试阅读:https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-and-action-selection 好像你有两个问题:

  1. 参数名称不同:

    routeTemplate: "api/{controller}/{action}/{id}"

但控制器将参数定义为“userId”,无法找到:

public IHttpActionResult GetProfilePicture(string userId)

它们必须匹配,以便您可以更改其中之一:

public IHttpActionResult GetProfilePicture(string id)
  1. 另一件事是大写问题。如上面的链接所示,使用小写字母。

其次 - 路径非常不稳定。 REST 是将数据视为资源,因此 url 的命名应仅包含资源。 您最好避免使用动词、函数名称和 CRUD 操作(请参阅:https://restfulapi.net/resource-naming/)。 此外 - 更好地使用小写字母(参见:Should a REST API be case sensitive or non case sensitive?

更好的 URL 示例如下:

    [HttpGet("api/users/{userId}/files/profile-picture")]

请注意,您还必须更改默认路由。 请试试这个并分享结果。

干杯!

【讨论】:

  • 我更改了参数名称,它仍然给我相同的响应
  • 问题是,在 Visual Studio 中一切正常,但是当我将控制器上传到 Plesk 到我的站点时,当我向它发出请求时它找不到控制器。
猜你喜欢
  • 2020-07-31
  • 2023-04-08
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 2015-08-13
相关资源
最近更新 更多