如何传递长度超过' 500'

时间:2016-01-27 20:21:22

标签: c# asp.net-mvc web-services

我已经建立了一个Web服务,可以从Android应用程序接收图像和图像名称的Base64string。我想将这些数据存储到我的sql server中。但是当我将此数据传递给Web服务时,我遇到了问题。这是我的网址: http://localhost:36690/api/Data/GetImage?base64String=/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCADIAMgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDg6K6v+zrP/n2j/Kj+zrP/AJ9o/wAqQrnKVp+Hv+QhJ/1yP8xWx/Z1n/z7R/lVHVo0srVZbVRDIX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96X/vof4Vqd6SkIzP7CtP70v8A30P8KP7CtP70v/fQ/wAK06UdfxoA559VubaR7eMJ5cLFFyvOAcDv7U3+27v+7F/3yf8AGqV5/wAf9z/11b+ZqKmM0v7bu/7sX/fJ/wAaP7bu/wC7F/3yf8azaKANy2tY9Wi+1XJYSE7fk4HHSpf7CtP70v8A30P8KXQf+Qb/AMDNaVIRmf2Faf3pf++h/hR/YVp/el/76H+FadFAGJdf8SXZ9kJPn53b+cY+mPWijxH1tf8Agf8ASigDGooopjCtPw9/yEJP+uR/mKKKAOhooopCCqup/wDIOn/3aKKAOUHQfSloopjCkPQ0UUAdt3pKKKQgpR1/GiigDj7z/j/uf+urfzNRUUUxhRRRQB0Wg/8AIN/4Ga0qKKQgooooAxfEfW1/4H/SiiigD//Z&imgName=dddd

这是我的问题enter image description here

这是我的网络服务

[HttpGet]
[ActionName("GetImage")]
public string GetImage(string base64String, string imgName)
{
    try
    {

        using (PhNetworkEntities context = new PhNetworkEntities())
        {
            pic pic = new pic();
            pic.path = base64String;
            pic.picname = imgName;
            context.pics.Add(pic);
            context.SaveChanges();
            return "Success";
        }

    }
    catch (DbEntityValidationException ex)
    {
        // Retrieve the error messages as a list of strings.
        var errorMessages = ex.EntityValidationErrors
                .SelectMany(x => x.ValidationErrors)
                .Select(x => x.ErrorMessage);

        // Join the list to a single string.
        var fullErrorMessage = string.Join("; ", errorMessages);

        // Combine the original exception message with the new one.
        var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

        // Throw a new DbEntityValidationException with the improved exception message.
        throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
    }
}

我不确定是代码问题还是web.config,所以这是我的web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>

    <add name="PhNetworkEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=ANDROIDDB;initial catalog=PhNetwork;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" maxQueryStringLength="2097151" maxUrlLength="2097151" maxRequestLength="2097151" />
    <authentication mode="None" />


    <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.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>

    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  <security>

    <requestFiltering>
      <requestLimits maxQueryString="5000000" maxAllowedContentLength="500000000" />
    </requestFiltering>
  </security>

  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>

</configuration>

请指教。谢谢你的时间。

2 个答案:

答案 0 :(得分:1)

查看您的错误消息,Web服务正常。您在pic.Path字段上有一个实体框架验证错误,其长度限制可能为500。最有可能是[StringLength(500)]

using (PhNetworkEntities context = new PhNetworkEntities())
{
  pic pic = new pic();
  pic.path = base64String; // <--- This field has a length validation of 500 on it.

也就是说,Querystrings并不适合发送图像,rule of thumb在查询字符串中是〜2000个字符,因此从长远来看,向[FromBody]方法迈进可能是有益的。

要发送大字符串,如果将其更改为:

public string GetImage([FromBody]string base64String, string imgName)

将其命名为

http://localhost:36690/api/Data/GetImage?imgName=dddd

但是在请求正文中传递大字符串:
例如。使用JSON,它将类似于:

{"base64String":"blah blah blah"}

答案 1 :(得分:0)

修改“GetImage”并尝试调用您的Web服务发送一个len&lt; 500

然后您可以看到问题是EF问题而且不是Web服务问题。

[ActionName("GetImage")]
public string GetImage(string base64String, string imgName)
{
    try
    {

        using (PhNetworkEntities context = new PhNetworkEntities())
        {
            pic pic = new pic();
            pic.path = new string('*', 502); // MODIFY!! Always FAILS!!!
            pic.picname = imgName;
            context.pics.Add(pic);
            context.SaveChanges();
            return "Success";
        }

    }
    catch (DbEntityValidationException ex)
    {
       // same as Question...
    }
}

也许是自动生成的代码。 检查数据库中表“pics”的设计,列路径 NVarchar(500)或Varchar(500)的支柱?

或者也可以在“PhNetworkEntities”中搜索,其中Max Length被分配给pic.path