簡體   English   中英

ASP.NET WebAPI - 未找到任何操作

[英]ASP.NET WebAPI - No action was found

我有以下代碼,但請求結束(Foo()/ Bar())總是在No action was found on the controller 'Device' that matches the request.

我在WebApiConfig中有一個自定義路由:

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

我的ASP.NET WebAPI控制器:

[HttpPost]
public void UpdateToken(string newToken)
{
    _deviceHandler.UpdateToken(newToken);
}

要查詢我的ASP.NET WebAPI,我正在使用RestSharp。

private static void Send(string resource, Method method, object payload)
{
    var client = new RestClient(baseUrl);
    var request = new RestRequest(resource, method);
    request.XmlSerializer = new JsonSerializer();
    request.RequestFormat = DataFormat.Json;
    request.AddBody(payload);

    var response = client.Execute(request);
    // ... handling response (exceptions, errors, ...)
}

public void Foo()
{
    var newToken = "1234567890";
    Send("/api/device/updatetoken", RestSharp.Method.POST, newToken );
}

public void Bar()
{
    var newToken = new { newToken = "1234567890" };
    Send("/api/device/updatetoken", RestSharp.Method.POST, newToken );
}

避免此錯誤的唯一方法是創建一個包含類的包裝類,其中包含屬性(get; set;),其名稱為controller參數(newToken)。

我有很多請求發送一個或兩個自定義字符串(未定義的長度)作為post(get的長度有限)。 但要為每個場景創建包裝器實現是真正的開銷! 我正在尋找另一種方式。

PS:我希望通過簡化方案我沒有犯任何錯誤=)

默認情況下,基元是從URI綁定的。 如果你想要一個原語來自正文,你應該使用[FromBody]屬性,如下所示:

[HttpPost]
public void UpdateToken([FromBody] string newToken)
{
    _deviceHandler.UpdateToken(newToken);
}

然后使用適當的格式化程序對字符串進行反序列化。 如果是JSON,請求正文應如下所示:

"1234567890"

暫無
暫無

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

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