Ошибка 400 от веб-сервиса - PullRequest
0 голосов
/ 01 июля 2011

Может кто-нибудь объяснить мне, почему я получаю ошибку http 400 при попытке опубликовать в моем веб-сервисе?

Мой сервисный контракт ::

[ServiceContract]
public interface IfldtWholesaleService {
    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Xml,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "MAC")]
    string MAC(string input);

Мой звонок;

    private void postToWebsite()
    {
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(txtUrl.Text);
        req.Method = "POST";
        req.MediaType = "text/xml";


        string input = "dfwa";
        req.ContentLength = ASCIIEncoding.UTF8.GetByteCount(input);

        StreamWriter writer = new StreamWriter(req.GetRequestStream());
        writer.Write(input);
        writer.Close();
        var rsp = req.GetResponse().GetResponseStream();

        txtOut.Text = new StreamReader(rsp).ReadToEnd();
    }

Файл конфигурации моего сервера

<system.serviceModel>
    <services>
        <service name="fldtRESTWebservice.fldtWholesaleService" behaviorConfiguration="httpBehaviour">
            <endpoint address="" binding="webHttpBinding" contract="fldtRESTWebservice.IfldtWholesaleService" behaviorConfiguration="httpEndpointBehavour">
                <identity>
                    <dns value="localhost"/>
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            <host>
                <baseAddresses>
                    <add baseAddress="http://localhost:8080/ContactService/"/>
                </baseAddresses>
            </host>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="httpBehaviour">
                <serviceMetadata httpGetEnabled="True"/>
                <serviceDebug includeExceptionDetailInFaults="False"/>
            </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
            <behavior name="httpEndpointBehavour">
                <webHttp/>
            </behavior>
        </endpointBehaviors>
    </behaviors>
</system.serviceModel>

EDIT :: также выдает ту же ошибку при использовании MediaType "text / plain"

Ответы [ 2 ]

3 голосов
/ 01 июля 2011

Ваш тип контента - text / xml, но ваш фактический контент - просто "dfwa".Это недопустимый документ XML.

(Кстати, вы также должны использовать блок using для req.GetResponse().)

1 голос
/ 01 июля 2011

Конечная точка с поведением webHttpBinding / webHttp по умолчанию принимает запросы в формате XML или JSON. И отправляемый вами XML-файл должен соответствовать ожиданиям службы. Код ниже отправляет запрос, который ожидает ваш сервис. Также обратите внимание, что вам нужно установить свойство ContentType в HttpWebRequest, а не MediaType .

public class StackOverflow_6550019
{
    [ServiceContract]
    public interface IfldtWholesaleService
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "MAC")]
        string MAC(string input);
    }

    public class Service : IfldtWholesaleService
    {
        public string MAC(string input)
        {
            return input;
        }
    }

    private static void postToWebsite(string url)
    {
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
        req.Method = "POST";
        req.ContentType = "text/xml";

        string input = @"<MAC xmlns=""http://tempuri.org/""><input>hello</input></MAC>";

        StreamWriter writer = new StreamWriter(req.GetRequestStream());
        writer.Write(input);
        writer.Close();
        var rsp = req.GetResponse().GetResponseStream();

        Console.WriteLine(new StreamReader(rsp).ReadToEnd());
    }

    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service/";
        WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        // To find out the expected request, using a WCF client. Look at what it sends in Fiddler
        var factory = new WebChannelFactory<IfldtWholesaleService>(new Uri(baseAddress));
        var proxy = factory.CreateChannel();
        proxy.MAC("Hello world");

        postToWebsite(baseAddress + "/MAC");

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...