(413)请求实体在WCF中过大 [英] (413) Request Entity Too Large in WCF

查看:354
本文介绍了(413)请求实体在WCF中过大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试这样发送数组大小为1227136并得到错误413



这是我从wreb应用程序发送数据 -

  protected void Page_Load(object sender,EventArgs e)
{
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(http:// localhost:59624 / RestServiceImpl.svc / PostFileRest); //本地
的路径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;

流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 +';扩展属性='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是空的!

var bites = httpRequest.TotalBytes;

//将流转换为字节数组
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将流转换为字节数组
private byte [] readRequest(流文件内容,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:UseTaskFriendlySynchronizationContextvalue =true/>
<! - < add key =wcf:serviceHostingEnvironment:useClassicReadEntityBodyModevalue =true/>
< / appSettings>
< system.web>
< compilation debug =truetargetFramework =4.5.1/>
< httpRuntime targetFramework =4.5.1/>
< httpModules>
<! - < add name =WcfReadEntityBodyModeWorkaroundModuletype =ForecastREST_API.WcfReadEntityBodyModeWorkaroundModule,ForecastREST_API/>
< / httpModules>
< /system.web>
< system.serviceModel>
< bindings>
< basicHttpBinding>
< binding name =myBindingmessageEncoding =TextmaxReceivedMessageSize =2147483647maxBufferSize =2147483647maxBufferPoolSize =2147483647transferMode =Streamed>
< readerQuotas maxDepth =64maxArrayLength =2147483647maxStringContentLength =2147483647/>
<! - 1227136 - >
< / binding>
< / basicHttpBinding>
< / bindings>
< services>
< service behaviorConfiguration =ForecastREST_API.RESTServiceImplBehaviorname =ForecastREST_API.RestServiceImpl>
< endpoint address =http:// localhost:59624 / RestServiceImpl.svcbinding =webHttpBindingcontract =ForecastREST_API.IRestServiceImplbehaviorConfiguration =Web>
<! - < endpoint address =http:// data-center:81 / ForecastREST_API / RestServiceImpl.svcbinding =webHttpBindingcontract =ForecastREST_API.IRestServiceImplbehaviorConfiguration =Web> - >
< identity>
<! - < dns value =localhost:59624/> - >

<! - < dns value =data-center:81/>
< / identity>
< / endpoint>
< endpoint address =mexbinding =mexHttpBindingcontract =IMetadataExchange/>
< / service>
< / services>
< behaviors>
< endpointBehaviors>
< behavior name =Web>
< dataContractSerializer maxItemsInObjectGraph =2147483647/>
< webHttp defaultOutgoingResponseFormat =JsonautomaticFormatSelectionEnabled =true/>
< dispatcherSynchronization asynchronousSendEnabled =true/>
< / behavior>
< / endpointBehaviors>
< serviceBehaviors>
< behavior name =ForecastREST_API.RESTServiceImplBehavior>
< dataContractSerializer maxItemsInObjectGraph =2147483647/>
< serviceMetadata httpGetEnabled =truehttpsGetEnabled =true/>
< serviceDebug includeExceptionDetailInFaults =false/>
< / behavior>
<! - < behavior name =>
< serviceMetadata httpGetEnabled =truehttpsGetEnabled =true/>
< serviceDebug includeExceptionDetailInFaults =false/>
< / behavior> - >
< / serviceBehaviors>
< / behaviors>
< protocolMapping>
< add binding =basicHttpsBindingscheme =https/>
< / protocolMapping>
< serviceHostingEnvironment aspNetCompatibilityEnabled =truemultipleSiteBindingsEnabled =false/>
< /system.serviceModel>
< modules runAllManagedModulesForAllRequests =true/>
<! -
要在调试期间浏览Web应用程序根目录,请将以下值设置为true。
在部署前设置为false,以避免泄露Web应用程序文件夹信息。
- >
< directoryBrowse enabled =true/>
<! - < modules>
< add name =WcfReadEntityBodyModeWorkaroundModuletype =ForecastREST_API.WcfReadEntityBodyModeWorkaroundModule,ForecastREST_API/>
< / modules> - >
< /system.webServer>

解决方案>

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



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

 < bindings> 
< webHttpBinding>
< binding name =myBindingmaxReceivedMessageSize =2147483647maxBufferSize =2147483647maxBufferPoolSize =2147483647transferMode =Streamed>
< readerQuotas maxDepth =64maxArrayLength =2147483647maxStringContentLength =2147483647/>
< / binding>
< / webHttpBinding>
< / bindings>
< services>
< service behaviorConfiguration =ForecastREST_API.RESTServiceImplBehaviorname =ForecastREST_API.RestServiceImpl>
< endpoint address =http:// localhost:59624 / RestServiceImpl.svcbinding =webHttpBindingcontract =ForecastREST_API.IRestServiceImplbehaviorConfiguration =WebbindingConfiguration =myBinding>
< / identity>
< / endpoint>
< endpoint address =mexbinding =webHttpBindingcontract =IMetadataExchange/>
< / service>
< / services>
< behaviors>
< endpointBehaviors>
< behavior name =Web>
< dataContractSerializer maxItemsInObjectGraph =2147483647/>
< webHttp defaultOutgoingResponseFormat =JsonautomaticFormatSelectionEnabled =true/>
< dispatcherSynchronization asynchronousSendEnabled =true/>
< / behavior>
< / endpointBehaviors>
< serviceBehaviors>
< behavior name =ForecastREST_API.RESTServiceImplBehavior>
< dataContractSerializer maxItemsInObjectGraph =2147483647/>
< serviceMetadata httpGetEnabled =truehttpsGetEnabled =true/>
< serviceDebug includeExceptionDetailInFaults =false/>
< / behavior>
< / serviceBehaviors>
< / behaviors>


Trying so send Array size of 1227136 and getting error 413

This is how I am sending the data from a wreb application-

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

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

I have only add bindingConfiguration="myBinding" and change basicHttpBinding to 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>

这篇关于(413)请求实体在WCF中过大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆