将xml发送到REST服务时收到错误请求(400)

时间:2015-04-27 07:04:26

标签: c# xml wcf rest

我第一次尝试使用XML服务和XML,我不断收到错误400(错误的请求)。 这是我的代码:

我有以下代表xml结构的类:

[DataContract(Namespace = "http://www.w3.org/2001/XMLSchema")]
public class GetLicenseParams
{
    [DataMember]
    public string FilePath { get; set; }

    public GetLicenseParams() { }

    public GetLicenseParams(string filePath)
    {
        FilePath = filePath;
    }
}

这就是我称之为方法的方式:

protected void btnGetLicense_Click(object sender, EventArgs e)
{
    MentorGraphicsAgent agent = new MentorGraphicsAgent();
    ltrLicences.Text = agent.GetLicense(new GetLicenseParams("MyFilePath"));
}

这是GetLicense方法:

public string GetLicense(GetLicenseParams @param)
{
    string requestUrl = string.Format("{0}GetLicense", "serviceurl", @param);
    return InvokePostRequest(requestUrl, @param);
}

以下是我如何调用请求以及我在哪里收到错误400:

protected string InvokePostRequest(string requestUrl, GetLicenseParams @params)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
        request.Method = "POST";
        request.ContentType = "application/xml; charset=utf-16";

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(GetLicenseParams));
        StringWriter stringWriter = new StringWriter();
        XmlWriter writer = XmlWriter.Create(stringWriter);
        xmlSerializer.Serialize(writer, @params);
        var xml = stringWriter.ToString();

        byte[] data = Encoding.UTF8.GetBytes(xml);
        using (Stream stream = request.GetRequestStream())
            stream.Write(data, 0, data.Length);

        HttpWebResponse resposne = (HttpWebResponse)request.GetResponse(); //Error 400 (bad request)
        using (StreamReader reader = new StreamReader(resposne.GetResponseStream()))
            return reader.ReadToEnd();
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

这是我的服务:

[ServiceContract(Namespace = "https://Services.Orbotech.com", ProtectionLevel = ProtectionLevel.None)]
public interface IMentorGraphics
{
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "GetLicense", RequestFormat = WebMessageFormat.Xml)]
    string GetLicense(GetLicenseParams @param);
}

最后,这是服务实施:

public string GetLicense(GetLicenseParams @param)
    {...}

0 个答案:

没有答案