WebGet的WCF ResponseFormat

mga*_*mer 23 c# wcf responseformat webget

WCF在ServiceContract中的WebGet批注中为ResponseFormat属性提供了两个选项.

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebGet(UriTemplate = "greet/{value}", BodyStyle = WebMessageBodyStyle.Bare)]
    string GetData(string value);

    [OperationContract]
    [WebGet(UriTemplate = "foo", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
    string Foo();
Run Code Online (Sandbox Code Playgroud)

ResponseFormat的选项是WebMessageFormat.Json和WebMessageFormat.Xml.是否可以编写自己的网络信息格式?我希望当客户端调用foo()方法时,他会获得原始字符串 - 没有json或xml包装器.

geo*_*tnz 48

尝试使用

BodyStyle = WebMessageBodyStyle.Bare
Run Code Online (Sandbox Code Playgroud)

然后从函数返回System.IO.Stream.

这是我用来从数据库中返回图像的一些代码,但可以通过URL访问:

[OperationContract()]
[WebGet(UriTemplate = "Person/{personID}/Image", BodyStyle = WebMessageBodyStyle.Bare)]
System.IO.Stream GetImage(string personID);
Run Code Online (Sandbox Code Playgroud)

执行:

public System.IO.Stream GetImage(string personID)
{
    // parse personID, call DB

    OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse;

    if (image_not_found_in_DB)
    {
        context.StatusCode = System.Net.HttpStatusCode.Redirect;
        context.Headers.Add(System.Net.HttpResponseHeader.Location, url_of_a_default_image);
        return null;
    }

    // everything is OK, so send image

    context.Headers.Add(System.Net.HttpResponseHeader.CacheControl, "public");
    context.ContentType = "image/jpeg";
    context.LastModified = date_image_was_stored_in_database;
    context.StatusCode = System.Net.HttpStatusCode.OK;
    return new System.IO.MemoryStream(buffer_containing_jpeg_image_from_database);
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,要返回原始字符串,请将ContentType设置为"text/plain"之类的内容,并将数据作为流返回.猜测,这样的事情:

return new System.IO.MemoryStream(ASCIIEncoding.Default.GetBytes(string_to_send));
Run Code Online (Sandbox Code Playgroud)

  • 尼斯.它工作 - 似乎应该有一个WebMessageFormat.Raw.谢谢. (4认同)

Eug*_*ota 8

WebGetAttribute由微软发货,我认为你不能扩展WebMessageFormat.但是你可以扩展WebHttpBinding它的用途WebGetAttribute.您可以添加自己的属性

[WebGet2(UriTemplate = "foo", ResponseFormat = WebMessageFormat2.PlainText)]
string Foo();
Run Code Online (Sandbox Code Playgroud)

通常,在WCF中自定义消息布局称为自定义消息编码器/编码.Microsoft提供了一个示例:自定义消息编码器:压缩编码器.人们另外做的另一个常见扩展是扩展行为以添加自定义错误处理,因此您可以在该方向上寻找一些示例.