簡體   English   中英

(413)WCF中的請求實體太大

[英](413) Request Entity Too Large in WCF

嘗試發送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>

我已經更改了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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM