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

时间:2013-02-28 10:06:04

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

我有以下代码,但请求结束(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:我希望通过简化方案=)

没有犯任何错误

1 个答案:

答案 0 :(得分:12)

默认情况下,基元是从URI绑定的。如果你想要一个原语来自正文,你应该使用[FromBody]属性,如下所示:

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

然后使用适当的格式化程序对字符串进行反序列化。如果是JSON,请求正文应如下所示:

"1234567890"
相关问题