简体   繁体   中英

ASP.net web api 2 Route-Attribute not working

I've the following problem, my route attribute is not working.

I have the following action:

[HttpGet]
[Route("~api/admin/template/{fileName}")]
public HttpResponseMessage Template(string fileName)
{
    return CreateHtmlResponse(fileName);
}

and i want to access the action like .../api/admin/template/login.html , so that Template get login.html passed as the file name.

But i alsways get: No HTTP resource was found that matches the request URI 'http://localhost:50121/api/admin/template/login.html' .

The following request works: /api/admin/template?fileName=login.html

Does anyone know, what i am doing wrong with my routing?

EDIT :

My route configuration

config.Routes.MapHttpRoute(
                    "API Default", "api/{controller}/{action}",
                    new { id = RouteParameter.Optional });
try adding a forward slash after the tilde
[HttpGet]
[Route("~/api/admin/template/{fileName}")]
public HttpResponseMessage Template(string fileName)
{
    return CreateHtmlResponse(fileName);
}

You have to call MapHttpAttributeRoutes() so that the Framework will be able to walk through your attributes and register the appropriate routes upon application start:

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

        // you can add manual routes as well
        //config.Routes.MapHttpRoute(...
    }
}

See MSDN

Check your Route attribute's namespace. It should be System.Web.Http instead of System.Web.Mvc .

验证您使用的是System.Web.Http.RouteAttribute而不是System.Web.Mvc.RouteAttribute

Try this routing in your WebApiConfig

        // Web API routes
        config.MapHttpAttributeRoutes();

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

You have to add RoutePrefix .

在我的Web API 2项目中,我不得不向控制器添加一个[RoutePrefix("events")] ,以便它获取动作路由属性。

In my case, I added Route("api/dashboard") to api controller. Changed it to RoutePrefix("api/dashboard") . And it works perfectly. Also you need config.MapHttpAttributeRoutes(); in webapiconfig.cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM