2017-08-17 68 views
2

作爲在MVC的Web API一個小白就可能有很明顯我錯過..自定義路線只是重定向到當前頁面

然而,在我ProjectController,我有以下方法與屬性(我知道這種方法應該是POST,但只是測試很容易...):

[Route("api/projects/archive/{id:int}")] 
[HttpGet]  
public void Archive(int id) 
{ 
    _projectService.Archive(id); 
} 

然而,當我打開我的網址,如:

http://localhost:49923/api/projects/archive/1 

頁面只是重定向到當前URL,並且不調用存檔方法。我也有一個斷點來驗證它沒有被擊中。

我最好的猜測是我也必須更新我的web api路由配置這是默認的,但我只是假設路由屬性是足夠的?

這裏是我的網頁API航線配置:

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

    // Web API routes 
    config.MapHttpAttributeRoutes(); 

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

    config.Formatters.JsonFormatter.SupportedMediaTypes 
     .Add(new MediaTypeHeaderValue("text/html")); 

} 

我在做什麼錯在這裏? :-)

EDITS:

Clearification 1 - 我ProjectController:

public class ProjectsController : ApiController 
{ 

    private ProjectService _projectService; 

    public ProjectsController() 
    { 
     _projectService = new ProjectService(); 
    } 

    [Route("api/projects/archive/{id:int}")] 
    [HttpGet] 

    public void Archive(int id) 
    { 
     _projectService.Archive(id); 
    } 
} 

Clearification 2 - 改:

因此,可以說我站在主頁(/)。然後我轉到網址「http://localhost:49923/api/projects/archive/1」,它會重新加載頁面並將其留在主頁。

+0

澄清'該頁面只是重定向到當前的URL,並沒有調用存檔方法。「目前尚不清楚。同時顯示控制器。 – Nkosi

+0

閱讀:https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api – Milney

回答

1

Web API配置配置正確。 確保控制器和行動的構築

public class ProjectController : ApiController { 

    //...other code removed for brevity 

    [HttpGet] 
    [Route("api/projects/archive/{id:int}")]//Matches GET api/projects/archive/1 
    public IHttpActionResult Archive(int id) { 
     _projectService.Archive(id); 
     return Ok(); 
    }  
} 
0

它有點晚了回答,但希望你覺得它有用,

很多時候,我們如何編寫代碼幫助的方式我們找到解決問題, 正如Nkosi已經回答,構建控制器和行動方法正確將解決問題。

它始終有助於首先檢查方法,而不是查看route.config,因爲默認情況下它將是相同的,除非您提供自定義屬性。

相關問題