WCF Restful返回HttpResponseMessage想要在设置内容时进行协商

我有一个WCF Restful服务,我希望这些方法返回HttpResponseMessage,因为它似乎是结构化的,而不仅仅是返回数据或exception或其他任何可能的方式。

我假设这是正确的,如果不让我知道,但我的问题是当我尝试设置HttpResponseMessage.Content时会发生什么。 当我这样做时,我在其中进行RESTful呼叫请求认证的客户端。

这是我的代码:

在界面中:

 [WebGet(UriTemplate = "/GetDetailsForName?name={name}" , ResponseFormat = WebMessageFormat.Json)] HttpResponseMessage GetDetailsForName(string name); 

在课堂里:

 public HttpResponseMessage GetDetailsForName(string name) { HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.OK) { //If I leave this line out, I get the response, albeit empty Content = new StringContent("Hi") }; return hrm; } 

我想尝试使用Request.CreateResponse但我似乎无法从我的WCF Restful方法获取请求。 OperationContext.Current.RequestContext没有CreateResponse。

有什么指针吗?

不幸的是,这不起作用。 演示的代码说:

构造一个HttpResponseMessage对象,使用JSON序列化程序对其进行序列化,并通过网络传递结果。

问题是HttpResponseMessage是一次性的,并不意味着序列化,而StringContent根本无法序列化。

至于为什么要重定向到身份validation表单 – 当服务无法序列化StringContent并返回400 HTTP状态代码时,该服务会抛出exception,该代码被解释为身份validation问题。

我有类似的错误,但不完全一样。 我试图序列化一个普通的对象,并得到一个net :: ERR_Conection_Reset消息。 wcf方法执行了7次,从未抛出exception。

我发现我必须注释我正在返回的类,以便我的JSON序列化程序能够理解如何序列化类。 这是我的wcf方法:

 [OperationContract] [WebGet( UriTemplate = "timeexpensemap", ResponseFormat = WebMessageFormat.Json)] public TimeexpenseMap timeexpensemap() { string sql = "select * from blah" DbDataReader reader = this.GetReader(sql); TimeexpenseMap tem = null; if (reader.Read()) { tem = new TimeexpenseMap(); // Set properties on tem object here } return tem; } 

我原来无法序列化的类没有注释:

 public class TimeexpenseMap { public long? clientid { get; set; } public int? expenses { get; set; } } 

带注释的类序列化没有问题:

 [DataContract] public class TimeexpenseMap { [DataMember] public long? clientid { get; set; } [DataMember] public int? expenses { get; set; } } 

如果我正在调用,例如一个公共字符串getDetails(int ID)并且抛出一个错误,这个工作……

 catch(Exception ex) { OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; response.StatusCode = System.Net.HttpStatusCode.OK; //this returns whatever Status Code you want to set here response.StatusDescription = ex.Message.ToString(); //this can be accessed in the client return "returnValue:-998,message:\"Database error retrieving customer details\""; //this is returned in the body and can be read from the stream }