C# 作为web api请求的一部分接收自定义对象

C# 作为web api请求的一部分接收自定义对象,c#,.net,asp.net-web-api,C#,.net,Asp.net Web Api,我正在通过web api公开一些数据。客户端是wpf应用程序,它以以下方式使用此服务 HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:11992/"); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));

我正在通过web api公开一些数据。客户端是wpf应用程序,它以以下方式使用此服务

 HttpClient client = new HttpClient();
 client.BaseAddress = new Uri("http://localhost:11992/");

 client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

 var url = "api/Data/;
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
           "Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
                string.Format("{0}:{1}", "myusername", "mypassword"))));                

HttpResponseMessage response = client.GetAsync(url).Result;
关于webapi端代码

 // GET: api/Data
 public IEnumerable<MyObject> Get()
 {
     return GetData().AsEnumerable();
 }
我的问题是:

是否可以接收自定义对象作为web api请求的一部分,以便我可以确定哪台计算机使用用户名访问web服务?

简而言之,是的

创建数据契约

[DataContract]
public class MyRequest
{
    [DataMember]
    public string myString { get; set; }
    [DataMember]
    public IEnumerable<string> myList { get; set; }
}

通过这种方式,您可以使用JSON对象进行post,它可以正常工作,只需注意放置正确的内容类型应用程序/JSON并使用post方法。

您可以通过路由/url和/或查询字符串进行操作,如果它是一个简单的id值,例如/api/entity/123或/api/entity/?id=123,或者如果它是一个更复杂的对象通常最好发送一个post请求,在那里可以发送反序列化到类中的json。这是否意味着我可以为该请求使用查询字符串值,如/api/entity/?username=john&computername=old Pc?是的,只要您的操作方法具有适当的签名,例如Getstring username、string computername。顺便说一句,不要引用查询字符串变量。使用/api/entity/?username=john而不是/api/entity/?username=john
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<MyResponse> MyGet(MyRequest request);