2017-08-10 97 views
0

我打电话给一个使用PostAsJsonAsync的MVC Api控制器。调用Api控制器PostAsJsonAsync简单类型参数

如果我想传递一个类似于类实例的复杂类型,它工作正常。但我需要通过一个简单的类型为string,或int

HttpResponseMessage response = await 
client.PostAsJsonAsync("http://localhost:62536/api/Controller/Method", "HELLO"); 

得到一个错误404 Method没有找到。

我WebApiController看起来像这样

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

我的API控制器的方法是这样的。

public void Method(string id){} 

如果尝试另一种Mehtod与Int类型如果我说值赋给一个复杂类型,像类不工作,要么..

HttpResponseMessage response = await 
    client.PostAsJsonAsync("http://localhost:62536/api/Controller/MethodA", 123); 

public void MethodA(int id){} 

..它工作正常。

仅限PostAsJsonAsync适用于复杂类型?它如何使它工作?

+0

的可能的复制[为什么我们必须指定FromBody和FromUri?](https://stackoverflow.com/questions/24625303/why-do-we-have-to-specify-frombody -and-fromuri) –

回答

1
public void Method([FromBody] string id){} 
0

看起来像解析问题。先创建字符串变量然后传递给方法。

string x = (string)value; 
+0

我已经试过这个...我修改了这个例子...谢谢 – Diego

+0

“http:localhost:8080, –

+0

Http:// localhost:8080 –

相关问题