【问题标题】:Internal Server Error 500 when using Web Api Http Put使用 Web Api Http Put 时出现内部服务器错误 500
【发布时间】:2017-05-25 17:29:44
【问题描述】:

我正在为一家使用 Picking Process 的公司开发 Webapp。

这个过程非常简单,我有一个包含一些信息的销售订单,我创建了一个包含一些信息的拣货清单(例如:商品数量、总重量和销售订单的 ID)。

我总是遇到这个错误

内部服务器错误

...当我尝试使用 PUT 方法时,创建一个 Picking List 并将其添加到 Web Api 端的数据库中。

当我删除 [HttpPost] 时,错误变为:

找不到方法

方法不允许

这是我的代码:

客户端

public async Task<bool> AddTarefa(ListasPicking listaPickingAdd) 
{
    String listaparaAdicionar = listaPickingAdd.idLista + ";" + listaPickingAdd.IDordemVenda + ";" + listaPickingAdd.peso + ";" + listaPickingAdd.itens;
    HttpResponseMessage response = await cliente.PutAsJsonAsync("api/ListasPicking/", listaparaAdicionar);

    return response.IsSuccessStatusCode;
}

Web Api 端 - 控制器

//PUT: api/ListasPicking
[ResponseType(typeof (ListasPicking))]
[HttpPut]
public  IHttpActionResult PutLista ([FromBody] String lista)
{
    if(!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    String[] result = lista.Split(';');
    ListasPicking novaLista = new ListasPicking();
    novaLista.idLista=result[0];
    novaLista.IDordemVenda = result[1];
    string lista_peso_converttoDouble = result[2];
    novaLista.peso = Convert.ToDouble(lista_peso_converttoDouble);
    string lista_items_converttoInt = result[3];
    novaLista.itens = Convert.ToInt32(lista_items_converttoInt);

    primContext.ListasPickingGet.Add(novaLista);
    primContext.SaveChanges();

    return StatusCode(HttpStatusCode.Created);
}

我尝试了一些与此类问题相关的解决方案,并且出现相同的错误。

Web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="PrimaveraRest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
  <!--    <remove name="WebDAV"/> -->

      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>

     <!-- <remove name="WebDAVModule"/> -->
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>


  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <applicationSettings>
    <PrimaveraRest.Properties.Settings>
      <setting name="Company" serializeAs="String">
        <value>DEMO</value>
      </setting>
      <setting name="User" serializeAs="String">
        <value>adminfixe</value>
      </setting>
      <setting name="Password" serializeAs="String">
        <value>123456</value>
      </setting>
    </PrimaveraRest.Properties.Settings>
  </applicationSettings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

更新

当我重建我的解决方案时,我得到了一些这样的行:

文件\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(1964,5): 警告 MSB3270:处理器之间不匹配 正在构建的项目架构“MSIL”和处理器 参考“Interop.ICrmDS800”、“x86”的架构。这 不匹配可能会导致运行时失败。请考虑更改 您的项目的目标处理器架构通过 配置管理器以调整处理器架构 在您的项目和参考之间,或依赖于 具有与目标相匹配的处理器架构的参考 您项目的处理器架构

可能是问题吗? Interop.dll 是我在项目中包含的一个文件,用于使用外部程序获取有关销售订单的信息。

解决方案

“ListaPicking”模型中缺少 [Key] 注释,并且我正在传递具有默认值的 DateTime 变量...我只是更改为例如 DateTime.Today,现在它正在工作:)

【问题讨论】:

  • 在尝试访问它的成员之前检查 result.Length。此外,如果您调试代码并将服务器端的异常添加到问题中会更好。

标签: c# asp.net-web-api asp.net-web-api-routing


【解决方案1】:

您调用PutAsJsonAsync,但是当它需要一个代表 json 的字符串时,您将一个非 json 字符串作为您的数据参数传递。

来自文档:

将 PUT 请求作为异步操作发送到指定的 Uri,并将给定的值序列化为 JSON。

要使其正常工作,请改为致电PutAsync

【讨论】:

  • 现在告诉字符串不能转换为 http.content。
  • @bullprog - 您应该能够在标题中设置content-type,使用application/x-www-form-urlencoded 并在字符串值前面加上=。见documentation
【解决方案2】:

你可以发送整个模型

public async Task<bool> AddTarefa(ListasPicking listaPickingAdd) {

    var response = await cliente.PutAsJsonAsync("api/ListasPicking/", listaPickingAdd);

    return response.IsSuccessStatusCode;        
}

并以相同的方式在动作中接收它,而不是解构和重建它。

[ResponseType(typeof (ListasPicking))]
[HttpPut]
public  IHttpActionResult PutLista ([FromBody] ListasPicking novaLista) {
    if(!ModelState.IsValid) {
        return BadRequest(ModelState);
    }

    primContext.ListasPickingGet.Add(novaLista);
    primContext.SaveChanges();

    return StatusCode(HttpStatusCode.Created);
}

【讨论】:

  • 我仍然收到错误...请查看我的更新!
  • @bullprog 遵循错误消息中提供的明确说明
  • 警告消失了,但我得到了同样的错误“内部服务器错误”。很抱歉浪费您的时间!
  • @bullprog 您需要准确缩小发生错误的位置。是调用动作还是在执行动作之前发生错误?如果它正在执行操作,则在其中放置一个 try catch,以查看在尝试保存记录时是否引发了错误。这可能会为您提供有关导致错误的原因的更多信息。
  • @bullprog 至少您已经缩小了引发错误的范围。什么是错误。它必须与您的数据存储(实体框架)相关
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-01
  • 2014-10-16
  • 2014-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
相关资源
最近更新 更多