簡體   English   中英

帶有自定義端點名稱的WEB API .NET Action

[英]WEB API .NET Action with custom endpoint names

所以我在.NET中設置了一個后端,基本的HTTP調用正在運行。 現在我需要一種替代方法,它不會通過ID搜索,而是通過屬性進行搜索,因此我想在最后使用不同的屬性進行REST調用。

以下是我的控制器的兩種方法:

public IHttpActionResult GetCategory(int id)
{
    var category = _productService.GetCategoryById(id);

    if (category == null) return NotFound();
    var dto = CategoryToDto(category);
    return Ok(dto);
}


public IHttpActionResult GetCategoryByName(string name)
{
    var category = _productService.GetCategoryByName(name);

    if(category == null) return NotFound();
    var dto = CategoryToDto(category);
    return Ok(dto);
}

我的API配置配置如下: /api/{controller}/{action}/{id}

所以第一個調用適用於這個調用: /api/category/getcategory/2

當我嘗試使用此調用的第二種方法時: /api/category/getcategorybyname/Jewelry

我收到錯誤消息,說我的控制器中沒有任何操作符合請求。

這有什么問題?

默認路由配置具有可選參數,其約束類型為int。 傳遞“珠寶”並不滿足這種約束。

最簡單的解決方法是將RouteAttribute應用於操作,並以這種方式指定參數。

[Route("api/category/getcategorybyname/{name}")]
public IHttpActionResult GetCategoryByName(string name)

確保您的WebConfig.cs文件具有使用行啟用的屬性路由

config.MapHttpAttributeRoutes();

您還可以通過將RoutePrefix("api/category")應用於控制器,然后從操作的Route屬性中剝離該部分來縮短RouteAttribute的操作名稱。

您還可以創建適用於控制器中所有操作的RoutePrefix規則,然后為每個操作應用特定的Route

[RoutePrefix("api/nestedSet")] //<<======
public class NestedSetController : ApiController
{
    [Route("myaction01")] //<<======
    [HttpGet]
    public async Task<int> Myaction01_differentName()
    {
       //the call will be: http://mydomain/api/nestedSet/myaction01
       //code here...
       return 0;
    }


    [Route("myaction02")] //<<======
    [HttpGet]
    public async Task<int> Myaction02_differentName()
    {
       //the call will be: http://mydomain/api/nestedSet/myaction02
       //code here...
       return 0;
    }
}

嘗試使用Route屬性修飾第二個方法

[Route("GetCategoryByName")]

然后在瀏覽器中調用此名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM