简体   繁体   English

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

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

Trying so send Array size of 1227136 and getting error 413 尝试发送1227136的数组大小并收到错误413

This is how I am sending the data from a wreb application- 这就是我从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

My WCF code where I am receiving the data when I am sending small amount of data then it is working fine. 当我发送少量数据时,我正在接收数据的WCF代码可以正常工作。 But I want to send large data. 但是我想发送大数据。

[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
}

My app.config- 我的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>

I have changed the WCf application app.config and solve the issue- 我已经更改了WCf应用程序app.config并解决了该问题-

I have only add bindingConfiguration="myBinding" and change basicHttpBinding to webHttpBinding. 我只添加bindingConfiguration =“ myBinding”并将basicHttpBinding更改为webHttpBinding。 Here is the new code- 这是新的代码-

<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.

相关问题 WCF服务(413)请求实体中的文件上传过大 - File upload in WCF Service (413) Request Entity Too Large 413 请求实体太大 - Web API - 413 request entity too large - Web API WCF服务异常远程服务器返回了意外的响应:(413)请求实体太大 - WCF Service Exception The remote server returned an unexpected response: (413) Request Entity Too Large 413:IIS Web 服务上的请求实体太大错误 - 413: Request Entity Too Large error on IIS webservice ASP.NET 核心捕获 HTTP 状态码 413 载荷太大/请求实体太大 - ASP.NET Core Capture HTTP Status Code 413 Payload Too Large / Request Entity Too Large 传递大字节时,WCF服务错误413“实体太大” [] - WCF Service Error 413 “Entity Too Large” when pass big byte[] 错误(413)请求实体太大 - error (413) request entity too larg 远程服务器返回了意外的响应:(413)请求实体太大(服务配置与客户端配置) - The remote server returned an unexpected response: (413) Request Entity Too Large (service config vs client config) asp.net web api:IIS8 - (413) 请求实体太大 - asp.net web api: IIS8 - (413) Request Entity Too Large 错误:远程服务器返回了意外的响应:(413)请求实体太大 - Error: the remote server returned an unexpected response: (413) Request Entity Too Large
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM