jQuery与WebApi一起使用 - 甚至不调用Controller方法

时间:2022-12-02 10:32:21

Sorry to ask a question about this so soon after asking another question but I'm now struggling with the PUT.

很抱歉在提出另一个问题之后很快就问这个问题,但我现在正在努力争取PUT。

I have a jQuery method which collects the data and passes it to a PUT function in the valuescontroller. But the controller isn't even being called (As I have a break point on it and it isn't breaking)

我有一个jQuery方法,它收集数据并将其传递给valuescontroller中的PUT函数。但控制器甚至没有被调用(因为我有一个断点,它没有打破)

Can I just check my jQuery is correct?

我可以检查一下我的jQuery是否正确?

var data = {
            id: truckId,
            obj: {
                TruckId: truckId,
                Reg: reg,
                Description: desc,
                Condition: condition
            }
        };
        var json = JSON.stringify(data)

        $.ajax({
            url: '/api/Values',
            type: 'PUT',
            contentType: "application/json; charset=utf-8",
            data: json,
            success: function (results) {
                $.getJSON("api/Values", LoadTrucks);
                alert('Truck Updated !');
            }
        })

The controller looks like this:

控制器看起来像这样:

public void Put(int id, TruckInfo obj)
    {
        WebApiTestEntities db = new WebApiTestEntities();

        var data = from item in db.TruckInfoes
                   where item.TruckId == id
                   select item;
        TruckInfo oldRecord = data.SingleOrDefault();
        oldRecord.Reg = obj.Reg;
        oldRecord.Description = obj.Description;
        oldRecord.Condition = obj.Condition;
        db.SaveChanges();
    }

Now it looks to me like that should at least be reaching the Controller. My guess is the parameters aren't being passed correctly and therefore it is looking for a different method but I can't see why or how to rectify that.

现在它看起来像我至少应该到达控制器。我的猜测是参数没有正确传递,因此它正在寻找一种不同的方法,但我不明白为什么或如何纠正它。

Any help would be greatly appreciated :)

任何帮助将不胜感激 :)

Lex

莱克斯

EDIT: As requested, further information.

编辑:根据要求,进一步的信息。

No Javascript errors on the error console.

错误控制台上没有Javascript错误。

The Console log displays the following:

控制台日志显示以下内容:

{"Message":"No HTTP resource was found that matches the request URI 'localhost:62997/api/Values'.","MessageDetail":"No action was found on the controller 'Values' that matches the request."}

{“Message”:“找不到与请求URI匹配的HTTP资源'localhost:62997 / api / Values'。”,“MessageDetail”:“在控制器上找不到与请求匹配的值'。}}

And under MessageDetail for the JSON console I get this (Which supports my theory on incorrect parameters I think)

在JSON控制台的MessageDetail下,我得到了这个(我认为这支持了我对不正确参数的理论)

"No action was found on the controller 'Values' that matches the request"

“未找到与请求相匹配的控制器'值'的操作”

The get however succeeds. (And the POST I got working earlier this morning.)

然而,获得成功。 (而今天上午早些时候我上班了。)

4 个解决方案

#1


18  

Change your code like below, then it will work fine:

如下所示更改您的代码,然后它将正常工作:

var data = {
        TruckId: truckId,
        Reg: reg,
        Description: desc,
        Condition: condition
    };

var json = JSON.stringify(data)

$.ajax({
    url: '/api/Values/' + truckId,
    type: 'PUT',
    contentType: "application/json; charset=utf-8",
    data: json,
    success: function (results) {

    }
})

The best practice when using REST is:

使用REST时的最佳做法是:

  1. User POST when creating new resource.
  2. 创建新资源时的用户POST。
  3. User PUT when updating existing resource and the Id of resource should be in the URL.
  4. 更新现有资源时的用户PUT和资源的Id应该在URL中。
  5. User DELETE when deleting existing resource and the Id of resource should be in query string as well.
  6. 用户删除现有资源时删除,资源的Id也应该在查询字符串中。

#2


5  

You are doing a PUT request without specifying the ID of the object.

您正在执行PUT请求而不指定对象的ID。

See here.

看这里。

the URI in a PUT request identifies the entity enclosed with the request

PUT请求中的URI标识请求附带的实体

Change

更改

url: '/api/Values',
type: 'PUT',

To

url: '/api/Values/' + truckId,
type: 'PUT',

The Routing engine will need to id to match to your method

路由引擎需要id才能与您的方法匹配

public void Put(int id, TruckInfo obj)

At the moment you are attempting to put this in your model here:

目前您正尝试将此项放入您的模型中:

id: truckId,
obj: {
   TruckId: truckId,
   //etc

But this will not work. Only one object is deserialisable from the body of the request.

但这不起作用。只有一个对象可以从请求的主体中解除序列化。

Simply alter your message payload to this

只需将您的消息有效负载更改为此

var data = {
            TruckId: truckId,
            Reg: reg,
            Description: desc,
            Condition: condition
           }

And use the correct url structure e.g.:

并使用正确的url结构,例如:

PUT http://localhost:62997/api/Values/1

#3


0  

You can use Firebug or similar browser plugins to check the request that is made and the response that the server gives.

您可以使用Firebug或类似的浏览器插件来检查所做的请求以及服务器提供的响应。

IIS could also be rejecting the PUT verb. I have run into the same problem. If this is the case, you should be able to fix it by changing or adding these handlers in your web.config file (section <system.webServer>):

IIS也可以拒绝PUT动词。我遇到了同样的问题。如果是这种情况,您应该可以通过在web.config文件中更改或添加这些处理程序来修复它( 部分):

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

#4


0  

add following configuration into your web.config file

将以下配置添加到web.config文件中

<system.webServer>
    <handlers>
      <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>
  </system.webServer>

#1


18  

Change your code like below, then it will work fine:

如下所示更改您的代码,然后它将正常工作:

var data = {
        TruckId: truckId,
        Reg: reg,
        Description: desc,
        Condition: condition
    };

var json = JSON.stringify(data)

$.ajax({
    url: '/api/Values/' + truckId,
    type: 'PUT',
    contentType: "application/json; charset=utf-8",
    data: json,
    success: function (results) {

    }
})

The best practice when using REST is:

使用REST时的最佳做法是:

  1. User POST when creating new resource.
  2. 创建新资源时的用户POST。
  3. User PUT when updating existing resource and the Id of resource should be in the URL.
  4. 更新现有资源时的用户PUT和资源的Id应该在URL中。
  5. User DELETE when deleting existing resource and the Id of resource should be in query string as well.
  6. 用户删除现有资源时删除,资源的Id也应该在查询字符串中。

#2


5  

You are doing a PUT request without specifying the ID of the object.

您正在执行PUT请求而不指定对象的ID。

See here.

看这里。

the URI in a PUT request identifies the entity enclosed with the request

PUT请求中的URI标识请求附带的实体

Change

更改

url: '/api/Values',
type: 'PUT',

To

url: '/api/Values/' + truckId,
type: 'PUT',

The Routing engine will need to id to match to your method

路由引擎需要id才能与您的方法匹配

public void Put(int id, TruckInfo obj)

At the moment you are attempting to put this in your model here:

目前您正尝试将此项放入您的模型中:

id: truckId,
obj: {
   TruckId: truckId,
   //etc

But this will not work. Only one object is deserialisable from the body of the request.

但这不起作用。只有一个对象可以从请求的主体中解除序列化。

Simply alter your message payload to this

只需将您的消息有效负载更改为此

var data = {
            TruckId: truckId,
            Reg: reg,
            Description: desc,
            Condition: condition
           }

And use the correct url structure e.g.:

并使用正确的url结构,例如:

PUT http://localhost:62997/api/Values/1

#3


0  

You can use Firebug or similar browser plugins to check the request that is made and the response that the server gives.

您可以使用Firebug或类似的浏览器插件来检查所做的请求以及服务器提供的响应。

IIS could also be rejecting the PUT verb. I have run into the same problem. If this is the case, you should be able to fix it by changing or adding these handlers in your web.config file (section <system.webServer>):

IIS也可以拒绝PUT动词。我遇到了同样的问题。如果是这种情况,您应该可以通过在web.config文件中更改或添加这些处理程序来修复它( 部分):

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

#4


0  

add following configuration into your web.config file

将以下配置添加到web.config文件中

<system.webServer>
    <handlers>
      <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>
  </system.webServer>