无法张贴的WebRequest如果内容长度> 7KB使用C# [英] Could not post on WebRequest if the Content Length > 7kb using C#

查看:189
本文介绍了无法张贴的WebRequest如果内容长度> 7KB使用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发布一个JSON给我们的Web服务。我的问题是,当我的request.ContentLength超过7KB。我会在request.GetResponse得到一个网络异常500()。但如果我的request.ContentLength低于7KB,我的职位是成功发送。



错误消息:

 远程服务器返回错误:( 500内部服务器错误。 

源代码:

 公共静态字符串JsonPost(字符串URL,字符串的方法,串POSTDATA)
{
URI地址=新的URI(URL +方法);
HttpWebRequest的要求= WebRequest.Create(地址)HttpWebRequest的;
request.Method =POST;
request.ContentType =应用/ JSON;
的byte [] byteData = UTF8Encoding.UTF8.GetBytes(POSTDATA);
request.ContentLength = byteData.Length;
使用(流postStream = request.GetRequestStream())
{
postStream.Write(byteData,0,byteData.Length);使用
}

{
(HttpWebResponse响应= request.GetResponse()作为HttpWebResponse)
{
StreamReader的读者=新的StreamReader(response.GetResponseStream ());
串JsonResponse = reader.ReadToEnd();
返回JsonResponse;
}
}
赶上(引发WebException前)
{
字符串消息=((System.Net.HttpWebResponse)(ex.Response))状态说明。
如果(message.Contains(忙))
返回消息;
,否则
抛出新的异常(消息);
}
}



Web.config文件:

 <?XML版本=1.0>?; 

<结构>
<的appSettings>
<添加键=网页:版本值=1.0.0.0/>
<添加键=ClientValidationEnabledVALUE =真/>
<添加键=UnobtrusiveJavaScriptEnabledVALUE =真/>
< /的appSettings>

<&的System.Web GT;
将;的httpRuntime executionTimeout =180的maxRequestLength =1048576useFullyQualifiedRedirectUrl =假minFreeThreads =8
minLocalRequestFreeThreads =4appRequestQueueLimit =100enableVersionHeader =真/>

<编译调试=真targetFramework =4.0>
<&集会GT;
<添加组件=System.Web.Abstractions,版本= 4.0.0.0,文化=中性公钥= 31BF3856AD364E35/>
<添加组件=System.Web.Helpers,版本= 1.0.0.0,文化=中性公钥= 31BF3856AD364E35/>
<添加组件=System.Web.Routing,版本= 4.0.0.0,文化=中性公钥= 31BF3856AD364E35/>
<添加组件=System.Web.Mvc,版本= 3.0.0.0,文化=中性公钥= 31BF3856AD364E35/>
<添加组件=System.Web.WebPages,版本= 1.0.0.0,文化=中性公钥= 31BF3856AD364E35/>
< /组件>
< /编译>

<身份验证模式=表格>
<形式loginUrl =〜/首页/无Cookie =自动检测超时=2880/>
< /认证>

<会员>
<供应商>
<清/>
<添加名称=AspNetSqlMembershipProviderTYPE =System.Web.Security.SqlMembershipProvider的connectionStringName =ApplicationServices
enablePasswordRetrieval =假enablePasswordReset设置=真requiresQuestionAndAnswer =假requiresUniqueEmail =假
maxInvalidPasswordAttempts =5minRequiredPasswordLength =6minRequiredNonalphanumericCharacters =0passwordAttemptWindow =10
的applicationName =//>
< /供应商>
< /会员>

<型材>
<供应商>
<清/>
<添加名称=AspNetSqlProfileProviderTYPE =System.Web.Profile.SqlProfileProvider的connectionStringName =ApplicationServices的applicationName =//>
< /供应商>
< / profile文件>

<启用roleManager =false的>
<供应商>
<清/>
<添加名称=AspNetSqlRoleProviderTYPE =System.Web.Security.SqlRoleProvider的connectionStringName =ApplicationServices的applicationName =//>
<添加名称=AspNetWindowsTokenRoleProviderTYPE =System.Web.Security.WindowsTokenRoleProvider的applicationName =//>
< /供应商>
< / roleManager>

<网页>
<&命名空间GT;
<添加命名空间=System.Web.Helpers/>
<添加命名空间=System.Web.Mvc/>
<添加命名空间=System.Web.Mvc.Ajax/>
<添加命名空间=System.Web.Mvc.Html/>
<添加命名空间=System.Web.Routing/>
<添加命名空间=System.Web.WebPages/>
< /命名空间>
< /页>
< /system.web>

< system.webServer>
<安全>
<的requestFiltering>
< requestLimits maxAllowedContentLength =1073741824/>
< /的requestFiltering>
< /安全>
<验证validateIntegratedModeConfiguration =FALSE/>
<模块runAllManagedModulesForAllRequests =真/>
< /system.webServer>

<运行>
< assemblyBinding的xmlns =瓮:架构 - 微软COM:asm.v1>
< dependentAssembly>
< assemblyIdentity名称=System.Web.Mvc公钥=31bf3856ad364e35/>
< bindingRedirect oldVersion =1.0.0.0-2.0.0.0NEWVERSION =3.0.0.0/>
< / dependentAssembly>
< / assemblyBinding>
< /运行>
< /结构>

异常日志:

 (System.Net.HttpWebResponse)(ex.Response){System.Net.HttpWebResponse} System.Net.HttpWebResponse 
基{System.Net.HttpWebResponse} System.Net.WebResponse {系统。 Net.HttpWebResponse}
字符集ISO-8859-1的字符串
ContentEncoding,串
CONTENTLENGTH 1047长
的ContentTypetext / html的串
饼干{系统.Net.CookieCollection} System.Net.CookieCollection
接头{
访问控制允许来源:*
的Content-Length:1047
的Cache-Control:私人
含量类型:text / html的
日期:星期二,2012年9月18日22时33分36秒GMT
的Set-Cookie:ASP.NET_SessionId = belurseo1i0ureppkspetw1a;路径= /;仅Http
服务器:Microsoft-IIS / 7.0
的X ASPNET-版本:4.0.30319
的X技术,通过:ASP.NET
} System.Net.WebHeaderCollection
IsMutuallyAuthenticated假布尔
上次更改{2012年9月19日上午6时34分07秒} System.DateTime的
法POST字符串
ProtocolVersion {1.1} System.Version
ResponseUri {HTTP://localhost/service.svc/Update}的System.Uri
服务器微软-IIS / 7.0的字符串
的StatusCode InternalServerError System.Net.HttpStatusCode
状态说明遇到服务器错误处理请求,请查看服务器日志以了解更多详细信息。字符串
SupportsHeaders真布尔


解决方案

试试这个:

 %WINDIR%\system32\inetsrv\appcmd设置配置-section:的requestFiltering -requestLimits.maxAllowedContentLength 1000000 

如果你只是想将其设置为你的应用程序:

 %WINDIR%\system32\inetsrv\appcmd设置配置默认Web站点/<您的应用程序与GT; -section:的requestFiltering -requestLimits.maxAllowedContentLength 1000000 

您可以找到更多的限制选项的这里



希望这有助于


I am trying to post a Json to our web service. My problem is that when my request.ContentLength exceeds 7kb. I will get a web exception 500 at request.GetResponse(). But if my request.ContentLength is below 7kb, my post is successfully sent.

Error Message:

 The remote server returned an error: (500) Internal Server Error.

Source code:

public static string JsonPost(string url, string method, string postData)
{
    Uri address = new Uri(url + method);
    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
    request.Method = "POST";
    request.ContentType = "application/json";
    byte[] byteData = UTF8Encoding.UTF8.GetBytes(postData);
    request.ContentLength = byteData.Length;
    using (Stream postStream = request.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
    }
    try
    {
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string JsonResponse = reader.ReadToEnd();
            return JsonResponse;
        }
    }
    catch (WebException ex)
    {
        string message = ((System.Net.HttpWebResponse)(ex.Response)).StatusDescription;
        if (message.Contains("busy"))
            return message;
        else
            throw new Exception(message);
    }
}

Web.config:

        <?xml version="1.0"?>

<configuration>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

  <system.web>
    <httpRuntime executionTimeout="180" maxRequestLength="1048576" useFullyQualifiedRedirectUrl="false" minFreeThreads="8"
    minLocalRequestFreeThreads="4" appRequestQueueLimit="100" enableVersionHeader="true" />

    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>

    <authentication mode="Forms">
      <forms loginUrl="~/Home/" cookieless="AutoDetect" timeout="2880" />
    </authentication>

    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Exception Logs:

    (System.Net.HttpWebResponse)(ex.Response)   {System.Net.HttpWebResponse}    System.Net.HttpWebResponse
    base    {System.Net.HttpWebResponse}    System.Net.WebResponse {System.Net.HttpWebResponse}
        CharacterSet    "ISO-8859-1"    string
        ContentEncoding ""  string
        ContentLength   1047    long
        ContentType "text/html" string
        Cookies {System.Net.CookieCollection}   System.Net.CookieCollection
        Headers {
            Access-Control-Allow-Origin: *
            Content-Length: 1047
            Cache-Control: private
            Content-Type: text/html
            Date: Tue, 18 Sep 2012 22:33:36 GMT
            Set-Cookie: ASP.NET_SessionId=belurseo1i0ureppkspetw1a; path=/; HttpOnly
            Server: Microsoft-IIS/7.0
            X-AspNet-Version: 4.0.30319
            X-Powered-By: ASP.NET
        }   System.Net.WebHeaderCollection
        IsMutuallyAuthenticated false   bool
        LastModified    {9/19/2012 6:34:07 AM}  System.DateTime
        Method  "POST"  string
        ProtocolVersion {1.1}   System.Version
        ResponseUri {http://localhost/service.svc/Update}   System.Uri
        Server  "Microsoft-IIS/7.0" string
        StatusCode  InternalServerError System.Net.HttpStatusCode
        StatusDescription   "The server encountered an error processing the request. Please see the server logs for more details."  string
        SupportsHeaders true    bool

解决方案

Try this:

%windir%\system32\inetsrv\appcmd set config -section:requestFiltering -requestLimits.maxAllowedContentLength:1000000

or if you only want to set it for your app:

%windir%\system32\inetsrv\appcmd set config "Default Web Site/<your app>" -section:requestFiltering -requestLimits.maxAllowedContentLength:1000000

You can find more limit options here.

Hope this helps

这篇关于无法张贴的WebRequest如果内容长度&GT; 7KB使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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