我想为客户端构建一个动态结构,以在 Web API 中询问服务器。我尝试使用以下代码来处理我的问题,但是它不起作用。
- 我怎样才能发送一个像
<travel>
服务一样的泛型类型- 如何更改服务器代码(或都需要更改客户端/服务器)?
PS:如果您将我的问题读到最后,感谢您的耐心等待。
客户代码
var serializer = new JavaScriptSerializer();
var product = new travel() { travel_desc = "select * from travel" };
var jsonText = serializer.Serialize(product);
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:65370/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StringContent content = new StringContent(jsonText, Encoding.UTF8, "application/json");
var z = client.PostAsync<travel>("api/bb", product, new JsonMediaTypeFormatter()).Result;
服务器代码,不起作用
public IHttpActionResult Post< T > (Object x) where T : new()
{
........................
}
顺便说一句没关系,但我不知道如何发送 <T> 到服务器
public IHttpActionResult Post(Object x)
{
........................
}
错误信息
Client call server, server will be getting an error message " StatusCode: 404, ReasonPhrase: 'Not Found' "
var z = client.PostAsync < travel > ("api/dd", product, new JsonMediaTypeFormatter()).Result; <--client
public class ddController< T > : ApiController {public virtual void Post() { ... } } <---server
// sorry all , my English isn't very well , so I will try to use code to tell everyone how i want
// in format situations,I will create 2 controller when I have 2 models(ex: users/product) , as following (client)
var a = client.PostAsync("api/users", users, new JsonMediaTypeFormatter()).Result;
var b = client.PostAsync("api/product", product, new JsonMediaTypeFormatter()).Result;
//and then when the users and product controllers was created the post code should be like as following (server)
public IHttpActionResult Postusers(users travel) {}
public IHttpActionResult Postproduct(product travel) {}
//now i just want to create 1 controller for above like as follwing
var b = client.PostAsync<users/product>("api/all", product, new JsonMediaTypeFormatter()).Result;(client)
public IHttpActionResult Post<T>(Object ForAll) where T : new() {} (server)