简体   繁体   English

使用Web Api Http Put时内部服务器错误500

[英]Internal Server Error 500 when using Web Api Http Put

I'm developing a Webapp to a company that use Picking Process. 我正在为使用Picking Process的公司开发一个Webapp。

The process is very simple, I have a sales order with some information, and i creating a picking list with some of that information (for example: number of items, total weight, and id of sales order). 这个过程非常简单,我有一个带有一些信息的销售订单,我创建了一个包含一些信息的拣配清单(例如:项目数,总重量和销售订单ID)。

I'm getting always this error 我总是得到这个错误

Internal Server Error 内部服务器错误

...when I'm trying to use PUT method, to create a Picking List and add it into a database in Web Api side. ...当我尝试使用PUT方法时,创建一个Picking List并将其添加到Web Api端的数据库中。

When I remove [HttpPost] the error change to : 当我删除[HttpPost] ,错误更改为:

Method Not Found 找不到方法

or 要么

Method Not Allowed 方法不允许

This is my code: 这是我的代码:

Client Side 客户端

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 Side - Controllers Web Api Side - 控制器

//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);
}

I trying some solutions related to this kind of problem, and the same error (s). 我尝试了一些与此类问题相关的解决方案,以及相同的错误。

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

UPDATE UPDATE

When I rebuild my solution, i'm getting some lines like this: 当我重建我的解决方案时,我得到一些像这样的行:

Files\\Microsoft Visual Studio\\2017\\Community\\MSBuild\\15.0\\Bin\\Microsoft.Common.CurrentVersion.targets(1964,5): warning MSB3270: There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "Interop.ICrmDS800", "x86". Files \\ Microsoft Visual Studio \\ 2017 \\ Community \\ MSBuild \\ 15.0 \\ Bin \\ Microsoft.Common.CurrentVersion.targets(1964,5):警告MSB3270:正在构建的项目的处理器体系结构“MSIL”与之间存在不匹配处理器体系结构的参考“Interop.ICrmDS800”,“x86”。 This mismatch may cause runtime failures. 这种不匹配可能会导致运行时故障。 Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project 请考虑通过Configuration Manager更改项目的目标处理器体系结构,以便在项目和引用之间调整处理器体系结构,或者依赖于具有与项目的目标处理器体系结构相匹配的处理器体系结构的引用

Can be the problem? 可能是问题? Interop.dll is a file that i include in my project to use a external program to get the information about sales order. Interop.dll是我在项目中包含的文件,用于使用外部程序获取有关销售订单的信息。

SOLUTION

The [Key] annotation is missing in "ListaPicking" Model, and i was passing a DateTime variable with default value... I just change to for example DateTime.Today and now it's working :) 在“ListaPicking”模型中缺少[Key]注释,我正在传递一个带有默认值的DateTime变量...我只是改为例如DateTime.Today,现在它正在工作:)

You call PutAsJsonAsync but then you pass a non json string as your data parameter when it expects a string that represents json. 您调用PutAsJsonAsync但是当它需要一个表示json的字符串时,您将传递非json字符串作为您的数据参数。

From the documentation: 从文档:

Sends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as JSON. 将PUT请求作为异步操作发送到指定的Uri,并将给定值序列化为JSON。

To make it work call PutAsync instead. 为了使其工作,请调用PutAsync

You could just send the entire model 你可以发送整个模型

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

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

    return response.IsSuccessStatusCode;        
}

And receive it at the action the same way instead of deconstructing and reconstructing it. 并以同样的方式接受它,而不是解构和重构它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM