问题描述:

No one knows how to edit records! Does no one perform this action? The POST, GET and DELETE all work but PUT, regardless of what you do, does not work. Does no one edit records using an Web API2 from ASP.NET?

I have used both Hurl.it and POSTMAN and neither one of them can perform an edit using PUT. It just produces a 400 error - there is no information about the error because there is nothing wrong with the request!

Is there someone in the world who has managed to edit records with this? When the bounty becomes available I will give as much as I can - please someone inform us how this action can be performed.

How has anyone not even noticed that this API does not work fully? I do nto know where else to ask! No one on the ASP.NET forums knows how to do it either.

HURL.IT

  1. yoururl/api/objects/id
  2. parameter fieldname: value (all)
  3. Click "Launch request"
  4. The field gets edited

In Web API 2 - 400 error... no other information (because there is nothing wrong with request)

POSTMAN - same as above (more or less)

Code inside controller:

// PUT: api/Table1s/5

[ResponseType(typeof(void))]

public IHttpActionResult PutTable1(int id, Table1 table1)

{

if (!ModelState.IsValid)

{

return BadRequest(ModelState);

}

if (id != table1.TestID)

{

return BadRequest();

}

db.Entry(table1).State = EntityState.Modified;

try

{

db.SaveChanges();

}

catch (DbUpdateConcurrencyException)

{

if (!Table1Exists(id))

{

return NotFound();

}

else

{

throw;

}

}

return StatusCode(HttpStatusCode.NoContent);

}

网友答案:

If your are using Attribute Routing, your controller could look something like this...

[RoutePrefix("api/Table1s")]
public class Table1Controller : ApiController {

    // PUT: api/Table1s/5
    [HttpPut]
    [Route("{id:int}")]
    [ResponseType(typeof(void))]
    public IHttpActionResult PutTable1(int id, [FromBody]Table1 table1) {...}

}

A request to that action might look like ...

PUT http://localhost:5076/api/Table1s/5 HTTP/1.1
User-Agent: Fiddler
Host: localhost:5076
Content-Type: application/json
Content-Length: 55

{
  "fieldname1":"value1",
  "fieldname2":"value2"
}

Make sure that you configured attribute routing along with your default configuration

//....
config.MapHttpAttributeRoutes()

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional },
);
//....
相关阅读:
Top