(413)在WCF中请求实体太大

时间:2016-07-12 09:38:00

标签: asp.net xml rest wcf c#-4.0

尝试发送数据大小为1227136并获得错误413

这就是我从wreb应用程序发送数据的方式 -

protected void Page_Load(object sender, EventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:59624/RestServiceImpl.svc/PostFileRest");//Path for local
        request.Timeout = Timeout.Infinite;
        request.KeepAlive = true;


        request.ContentType = "application/vnd.ms-excel";
        /*---------------------------------------------------------------------------*/
        string excelTojson = excelToJson();

        byte[] fileData = Encoding.ASCII.GetBytes(excelTojson);
        /*---------------------------------------------------------------------------*/

        request.ContentLength = fileData.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileData, 0, fileData.Length);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        System.Diagnostics.Debug.Assert(response.StatusCode == HttpStatusCode.OK);

        string responseMessage = string.Empty;
        using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
        {
            responseMessage = sr.ReadToEnd();
        }
        Response.Write(responseMessage);
    }

    #region excelToJson
    public string excelToJson()
    {
        var pathToExcel = @"E:\My_Work\MVC\Test1.xlsx";

        OleDbConnection MyConnection;
        DataTable dt;
        OleDbDataAdapter MyCommand;
        MyConnection = new OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + pathToExcel + "';Extended Properties='Excel 12.0 Xml;HDR=YES'");
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
        MyCommand.TableMappings.Add("Table", "TestTable");
        dt = new DataTable();
        MyCommand.Fill(dt);
        MyConnection.Close();

        string jsonString = string.Empty;
        return jsonString = JsonConvert.SerializeObject(dt);
    }
    #endregion

我的WCF代码,当我发送少量数据时,我正在接收数据,然后它正常工作。但我想发送大量数据。

[ServiceContract]
public interface IRestServiceImpl
{
    [OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "PostFileRest")]
    string PostFileRest(Stream fileContents);
}
public class RestServiceImpl : IRestServiceImpl
{
    public string PostFileRest(Stream fileContents)
    {
        var httpRequest = HttpContext.Current.Request;

        //var filePath = "C:\\file.xls";  //excel filePath for local
        //var filePath = "D:\\Forecast\\ExcelOutput\\output.xls";  //excel filePath for 19 server

        //StreamReader r = new StreamReader(HttpContext.Current.Request.InputStream);
        //string jsonBody = r.ReadToEnd();  // jsonBody is empty!!

        var bites = httpRequest.TotalBytes;

        //Convert stream to byte array
        byte[] reqBytes = readRequest(fileContents, bites);
        byte[] decodedReqBytes = HttpUtility.UrlDecodeToBytes(reqBytes);

        string json = System.Text.Encoding.UTF8.GetString(reqBytes);
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);

        //MemoryStream stream = new MemoryStream(reqBytes);
        //FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
        //stream.WriteTo(file);
        //file.Close();
        //stream.Close();

        string responseJson = TalkToDll.ForecastData(dt);

        return responseJson;
    }

    #region Convert Stream to byte array
    private byte[] readRequest(Stream fileContents, int bites)
    {
        System.IO.MemoryStream memStream = new System.IO.MemoryStream();
        int BUFFER_SIZE = bites;
        int iRead = 0;
        int idx = 0;
        Int64 iSize = 0;
        memStream.SetLength(BUFFER_SIZE);
        while (true)
        {
            byte[] reqBuffer = new byte[BUFFER_SIZE];
            try
            {
                iRead = fileContents.Read(reqBuffer, 0, BUFFER_SIZE);
            }
            catch (System.Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }

            if (iRead == 0)
            {
                break;
            }

            iSize += iRead;
            memStream.SetLength(iSize);
            memStream.Write(reqBuffer, 0, iRead);
            idx += iRead;
        }

        byte[] content = memStream.ToArray();
        memStream.Close();
        return content;
    }
    #endregion
}

我的app.config -

<?xml version="1.0"?>

<appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    <!--<add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true"/>-->
</appSettings>
<system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1"/>
    <httpModules>
        <!--<add name="WcfReadEntityBodyModeWorkaroundModule" type="ForecastREST_API.WcfReadEntityBodyModeWorkaroundModule, ForecastREST_API" />-->
    </httpModules>
</system.web>
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="myBinding" messageEncoding="Text" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" transferMode="Streamed" >
                <readerQuotas maxDepth="64" maxArrayLength="2147483647" maxStringContentLength="2147483647"/>
                <!--1227136-->
            </binding>
        </basicHttpBinding>
    </bindings>
    <services>
        <service behaviorConfiguration="ForecastREST_API.RESTServiceImplBehavior" name="ForecastREST_API.RestServiceImpl">
            <endpoint address="http://localhost:59624/RestServiceImpl.svc" binding="webHttpBinding" contract="ForecastREST_API.IRestServiceImpl" behaviorConfiguration="Web">
                <!--<endpoint address="http://data-center:81/ForecastREST_API/RestServiceImpl.svc" binding="webHttpBinding" contract="ForecastREST_API.IRestServiceImpl" behaviorConfiguration="Web">-->
                <identity>
                    <!--<dns value="localhost:59624"/>-->

                    <!--<dns value="data-center:81"/>-->
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="Web">
                <dataContractSerializer maxItemsInObjectGraph="2147483647" />
                <webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
                <dispatcherSynchronization asynchronousSendEnabled="true" />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="ForecastREST_API.RESTServiceImplBehavior">
                <dataContractSerializer maxItemsInObjectGraph="2147483647" />
                <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
            <!--<behavior name="">
 <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
 <serviceDebug includeExceptionDetailInFaults="false" />
</behavior>-->
        </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
</system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
    To browse web app root directory during debugging, set the value below to true.
    Set to false before deployment to avoid disclosing web app folder information.
  -->
    <directoryBrowse enabled="true"/>
    <!--<modules>
        <add name="WcfReadEntityBodyModeWorkaroundModule" type="ForecastREST_API.WcfReadEntityBodyModeWorkaroundModule, ForecastREST_API" />
    </modules>-->
</system.webServer>

1 个答案:

答案 0 :(得分:1)

我已经更改了WCf应用程序app.config并解决了问题 -

我只添加bindingConfiguration =“myBinding”并将basicHttpBinding更改为webHttpBinding。 这是新代码 -

<bindings>
        <webHttpBinding>
            <binding name="myBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" transferMode="Streamed" >
                <readerQuotas maxDepth="64" maxArrayLength="2147483647" maxStringContentLength="2147483647"/>
            </binding>
        </webHttpBinding>
    </bindings>
    <services>
        <service behaviorConfiguration="ForecastREST_API.RESTServiceImplBehavior" name="ForecastREST_API.RestServiceImpl">
            <endpoint address="http://localhost:59624/RestServiceImpl.svc" binding="webHttpBinding" contract="ForecastREST_API.IRestServiceImpl" behaviorConfiguration="Web" bindingConfiguration="myBinding">
                </identity>
            </endpoint>
            <endpoint address="mex" binding="webHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="Web">
                <dataContractSerializer maxItemsInObjectGraph="2147483647" />
                <webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
                <dispatcherSynchronization asynchronousSendEnabled="true" />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="ForecastREST_API.RESTServiceImplBehavior">
                <dataContractSerializer maxItemsInObjectGraph="2147483647" />
                <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
        </serviceBehaviors>
    </behaviors>