c# Asp.net Web API 属性路由404错误

c# Asp.net Web API Attribute Routing 404 Error

我无法弄清楚为什么我的属性路由不起作用,第一个操作方法有效但第二个无效。

这是我的设置:

public class ActivMobileController : ApiController
{
    [HttpGet]
    [Route("api/ActivMobile/Impact/{token}")]
    public IHttpActionResult Impact(string token)
    {
     ...   
    }

    [HttpGet]
    [Route("api/ActivMobile/Attachments/{id}")]
    public IHttpActionResult Attachments(string id)
    {
     ...
    }
 }

这是我的 WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Reference: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
        config.EnableCors(new EnableCorsAttribute(CloudConfigurationManager.GetSetting("AllowOrigins"), "*", "*"));

        // Web API routes
        config.MapHttpAttributeRoutes();

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

这是 URL 即时通讯测试,它给出了 404 错误

http://localhost:60105/api/ActivMobile/Attachments/39E522838A652508112E9AD1E0E831C7

您在默认模板中已经指定 API 两次

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

从你的路线中删除多余的Api/activMobile

[Route("Impact/{token}")]
public IHttpActionResult Impact(string token)
{
 ...   
}

[HttpGet]
[Route("Attachments/{id}")]
public IHttpActionResult Attachments(string id)
{
 ...
}