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

标签 c# asp.net web-services wcf rest

我有一个 WCF Restful 服务,我想要返回 HttpResponseMessage 的方法,因为它看起来是结构化的,而不是仅仅返回数据或异常或任何其他可能到达那里的东西。

我假设这是正确的,如果不让我知道,但我的问题是当我尝试设置 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 方法获取 Request。 OperationContext.Current.RequestContext 没有 CreateResponse。

有什么建议吗?

最佳答案

不幸的是,这行不通。演示代码说:

Construct an HttpResponseMessage object, serialize it with a JSON serializer and pass the result over the wire.

问题是 HttpResponseMessage 是一次性的,不能序列化,而 StringContent 根本不能序列化。

至于为什么您被重定向到身份验证表单 - 服务在无法序列化 StringContent 时抛出异常 并返回 400 HTTP 状态代码,该代码被解释为身份验证问题。

关于c# - WCF Restful返回HttpResponseMessage想在设置内容时进行协商,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32595583/

相关文章:

c# - IoC 和绑定(bind)到接口(interface)

c# - 插入时防止重复

html - ASP.NET:以编程方式插入表格单元格

c# - 无法在 Azure C# 上创建存储帐户

wcf - 将用户名和密码传递给 svcutil.exe?

css - 如何拉伸(stretch)背景内容?

c# - ASP.NET WebAPI : Aborted (cancelled) requests

c# - JSON 字符串不填充对象的基本属性 (MVC 4)

c# - ASP.net MVC 强类型 View 下拉列表为空

java - 如何在 Glass Fish Server/Apache Tomcat 上部署 Rest Web 服务?