WCF Restful返回HttpResponseMessage想要在设置内容时进行协商 [英] WCF Restful returning HttpResponseMessage wants to negotiate when setting content

查看:92
本文介绍了WCF Restful返回HttpResponseMessage想要在设置内容时进行协商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a WCF Restful service and I would like the methods to return HttpResponseMessage because it seems structured rather than just returning the data or the exception or whatever else might make its way there.

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

I am assuming this is a correct, if not let me know, but my problem is what happens when I try to set HttpResponseMessage.Content. When I do this, the client in which I made the RESTful call request authentication.

这是我的代码:

在界面中:

[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.

I wanted to try to use Request.CreateResponse but I can't seem to get to Request from my WCF Restful method. OperationContext.Current.RequestContext does not have CreateResponse.

有指针吗?

推荐答案

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

Unfortunately this will not work. The demonstrated code says:

构造一个 HttpResponseMessage 对象,使用JSON序列化器对其进行序列化,然后将结果通过导线传递.

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

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

The problem is HttpResponseMessage is disposable and not meant to be serialized, while StringContent cannot be serialized at all.

关于为什么您被重定向到身份验证表单-当服务无法序列化 StringContent 时,服务将引发异常并返回一个400 HTTP状态代码,该代码被解释为身份验证问题.

As to why you are redirected to an authentication form - the service throws an exception when it cannot serialize StringContent and returns a 400 HTTP status code which gets interpreted as an authentication issue.

这篇关于WCF Restful返回HttpResponseMessage想要在设置内容时进行协商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆