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

时间:2019-05-20 16:13:42

标签: c# routing asp.net-web-api-routing

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

这是我的设置:

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

1 个答案:

答案 0 :(得分:0)

您已经在默认模板中指定了两次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)
{
 ...
}