简体   繁体   English

在C#中将JSON字符串发布到RESTful WCF服务时,返回400(错误请求)或空数据

[英]400 (Bad Request) or empty data when POSTing JSON string to RESTful WCF service in C#

I got stuck sending data to a self hosted web service. 我无法将数据发送到自托管的Web服务。 What I got so far: 我到目前为止所得到的:

The Service contract and implementation (btw. GET works like a charm) 服务合同和实施(顺便说一下,GET的作用就像一个魅力)

[WebGet( UriTemplate = "/gast/{customer_id}/{year}/{gast_id}", ResponseFormat = WebMessageFormat.Json )]
[OperationContract]
public acsEintrittGast GetGastInfo( string customer_id, string year, string gast_id ) {
    acsEintrittGast gast = new acsEintrittGast();
    gast.ID = Guid.Parse( gast_id );
    gast.Bitmap = File.ReadAllBytes( dataPath + customer_id + "\\" + year + "\\" + gast_id + ".jpg" );
    return gast;
}

[WebInvoke( UriTemplate = "/gast/{customer_id}/{year}", 
    ResponseFormat = WebMessageFormat.Json, 
    RequestFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Wrapped,
    Method = "POST" )]

[OperationContract]
public acsEintrittGast SetGastInfo( string customer_id, string year, acsEintrittGast GastObject /*string GastString*/ ) {
    acsEintrittGast Gast = null;
    try {
        //Gast = JsonConvert.DeserializeObject<acsEintrittGast>( (string)GastObject);
        File.WriteAllBytes( dataPath + customer_id + "\\" + year + "\\" + Gast.ID.ToString() + ".jpg", Gast.Bitmap.ToArray<byte>() );
    }
    catch {
    }
    return Gast;
}

The service consumer method (running on windows phone 8.1) 服务使用者方法(在Windows Phone 8.1上运行)

public async static Task<T> SetRESTData( string URI, T Content ) {
    T res = default( T );

    HttpClient httpClient = null;
    HttpResponseMessage response = null;
    StreamReader sr  = null;
    StreamWriter writer = null;
    MemoryStream ms = null;
    try {
        httpClient = new HttpClient();

        string s = JsonConvert.SerializeObject( Content );
        StringContent theContent = new StringContent( s, System.Text.Encoding.UTF8, "application/json" );

        using( HttpRequestMessage request = new HttpRequestMessage( HttpMethod.Post, BaseURI + URI ) ) {
            request.Content = theContent;
            response = await httpClient.SendAsync( request );
        }
    }
    catch {
    }
    finally {
        if( sr != null ) {
            sr.Close();
            sr = null;
        }
        if( writer != null ) {
            writer.Close();
            writer = null;
        }
        if( ms != null ) {
            ms.Dispose();
            ms = null;
        }
        if( response != null ) {
            response.Dispose();
            response = null;
        }
        if( httpClient != null ) {
            httpClient.Dispose();
            httpClient = null;
        }
    }
    return res;
}

And finally the data 最后是数据

[DataContract( Name = "acsEintrittGast", Namespace = "" )]
public class acsEintrittGast {
    private Guid id = Guid.NewGuid();
    [DataMember( Name = "id", Order = 1 )]
    public Guid ID {
        get { return id; }
        set { id = value; }
    }

    private Byte[] bitmap = null;
    [DataMember( Name = "bitmap", Order = 1 )]
    public Byte[] Bitmap {
        get { return bitmap; }
        set { bitmap = value; }
    }

    private DateTime lastEntry = new DateTime( 1900, 1, 1 );
    [DataMember( Name = "lastEntry", Order = 1 )]
    public DateTime LastEntry {
        get { return lastEntry; }
        set { lastEntry = value; }
    }
}

When I try to send a simple instance 当我尝试发送一个简单的实例时

acsEintrittGast gast = new acsEintrittGast();
gast.Bitmap = new byte[80455];
gast.ID = Guid.NewGuid();
await acsService.SetGastInfo( ftpLicID, currentYear, gast );

it depends on what I try out changing some parameters I get either "400 Bad Request" or the GastObject is null. 这取决于我尝试更改某些参数而得到的错误,即“ 400 Bad Request”或GastObject为null。 I also tried to declare a string as parameter, but this is also null. 我还尝试将字符串声明为参数,但这也为null。 Please don't answer "use the search function". 请不要回答“使用搜索功能”。 I do nothing else than searching for an answer for the last 3 days ;) Any hints are welcome! 除了搜索最近3天的答案外,我什么也没有做;)欢迎任何提示! Thanks in advance... 提前致谢...

You try to send the simple instance by calling "SetGastImfo" 您尝试通过调用“ SetGastImfo”发送简单实例
the implementation is "SetGastInfo" 实现是“ SetGastInfo”
Sure it's not a typo? 确定不是错字吗?

The Answer is as simple as it is difficult to find: Only send data that is supported by JSON! 答案很简单,因为很难找到它:仅发送JSON支持的数据! I tried to send a byte array called bitmap. 我试图发送一个称为位图的字节数组。 But byte arrays are not supported by JSON. 但是JSON不支持字节数组。 If you want to send a byte array, you need to transform it into a string with BASE64 encoding. 如果要发送字节数组,则需要将其转换为具有BASE64编码的字符串。 So do not decorate the bitmap as DataMember, instead use this solution: 因此,请勿将位图装饰为DataMember,而应使用以下解决方案:

private Byte[] bitmap = null;
    public Byte[] Bitmap {
        get { return bitmap; }
        set { bitmap = value; }
}

[DataMember]
public string BitmapBASE64 {
    get {
        return Convert.ToBase64String( bitmap );
    }
    set {
        bitmap = Convert.FromBase64String( value );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM