18

I'm trying to update data using WebApi PUT method. My code working fine before, but suddenly I start to get this error.

"Message":"The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'xEmployee' from content with media type 'application/octet-stream'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException".

This is headers: Response Header.

HTTP/1.1 415 Unsupported Media Type
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
Set-Cookie: Role=D65520F37D105E39C1A92C15CD482E378F32A769592AC7D8305285A5B9B90362F7F2F13F14E6DC220E44D26940B06B52E7460EF13184F245805AF9523D1072464F4BD06AFB4F8AEB8B7D8BF607A8922C6041A3A4C636BF3B26388E606A94FE43; expires=Tue, 07-Oct-2014 09:49:56 GMT; path=/
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 07 Oct 2014 09:19:56 GMT
Content-Length: 809

Request Header:

PUT /api/xemployees/2110481232 HTTP/1.1
Host: guideonline.ilvestour.office
Connection: keep-alive
Content-Length: 229
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://guideonline.ilvestour.office
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
Content-Type: application/json; charset=UTF-8"
Referer: http://guideonline.ilvestour.office/account
Accept-Encoding: gzip,deflate,sdch
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: .ASPXAUTH=215C424A0A023F5B42775B7A73B08FEC8CB36E7200FBA430EADF2F300A84500571F8B5EE980C3EF2913FE160978973CDBC50BDD216E16FC342EF0B566D0944ECFD901DF471DEF9F6E5D272B52F2450CC0A1FB96BCC6B3B6E7A7C07343D4DFBD66; Role=DE678EE89D7089B8CD74B202E00C53CA9AE9E4C40B506C5C4EEF56E7962F38ED86F6BFD34E5FD3A6DD6ECCCF61AF768CAB0C1D7C5F15A8638F9454B24DF3208F021EB638235420574C6420CA5A19F0B6BD07BAC303FF79612D6C1AF246563A7
Request Payloadview source
{"Kod":2110481232, "Сотрудник": "Lena", "Telephon": "088-6734227", "Password":"rimosa57", "email":"samoylova-elena@mail.ru", "CrWho":"OMEGA.Administrator", "CrWhen":"2014-10-07T09:20:05.735Z"}

Nothing special in Controller code:

[Authorize(Roles = "Admin, User")]
        public async Task<IHttpActionResult> PutxEmployee(int id, xEmployee xEmployee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != xEmployee.Kod)
            {
                return BadRequest();
            }

            try
            {
                var user = db.xEmployee.Find(id);
                user.Сотрудник = xEmployee.Сотрудник;
                user.Telephon = xEmployee.Telephon;
                user.Password = xEmployee.Password;
                user.email = xEmployee.email;
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!xEmployeeExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    var path = "C:/error.txt";
                    using (StreamWriter sw = File.CreateText(path))
                    {
                        sw.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    }
                    using (StreamWriter sw1 = File.CreateText("C:/error1.txt"))
                        foreach (var ve in eve.ValidationErrors)
                        {
                            sw1.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                ve.PropertyName, ve.ErrorMessage);
                        }
                }
                throw;
            }
            return StatusCode(HttpStatusCode.NoContent);
        }

Same as WebApiConfig:

public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.Culture = new CultureInfo("ru-RU");
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
andrey.shedko
  • 3,128
  • 10
  • 61
  • 121
  • It seems that the request doesn't have a content type header. Have a look at this post: http://truncatedcodr.wordpress.com/2012/09/05/asp-net-web-api-always-set-content-type/ – elolos Oct 07 '14 at 09:41
  • I'm not sure. As you can see from this Accept: application/json, text/javascript, */*; q=0.01 this is show what kind of content I'm expecting to get. Or it's something different? – andrey.shedko Oct 07 '14 at 09:44
  • I think that the Accept header is not necessary in web api as `application/json` is the default. According to the post I've mentioned though, the Content-Type header should be present in the request, otherwise it is inferred by the server to be `application/octet-stream` – elolos Oct 07 '14 at 09:54
  • @elolos, I* got your point, but please take look at my Content-Type string in Request Header - Content-Type: application/json; charset=UTF-8" – andrey.shedko Oct 07 '14 at 09:56
  • 1
    Sorry, I must have missed this line. Could the `"` character be a typo? – elolos Oct 07 '14 at 09:57
  • Seemed like this is source of problem. There is erro 400 now, but this problem I can solve. Please add your comment as answer. – andrey.shedko Oct 07 '14 at 10:07

3 Answers3

20

There seems to be a typo (last ") in the request's Content-Type header:

Content-Type: application/json; charset=UTF-8"

When this header is missing or malformed, the server will automatically use application/octet-stream by default, as described by this post.

Community
  • 1
  • 1
elolos
  • 4,310
  • 2
  • 28
  • 40
3

I were facing similar problem. Though i have a Content-Type declare it was still sending same error. What I did is added Accept Header and it started working.

Accept: application/json
Content-Type: application/json
Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93
1

Also, make sure there's only one header Content-Type. In my case, my rest client was implicitly sending the empty Content-Type which got overridden by Content-Type: application/json hence the error.

GorvGoyl
  • 42,508
  • 29
  • 229
  • 225