Web API not receiving the json of serialized objectHTTP header is being sent, but isn't present in Request.HeadersDeep cloning objectsHow do I format a Microsoft JSON date?ASP.NET Web Site or ASP.NET Web Application?JavaScriptSerializer - JSON serialization of enum as stringDeserialize JSON into C# dynamic object?WCF vs ASP.NET Web APIHow do I get ASP.NET Web API to return JSON instead of XML using Chrome?How to secure an ASP.NET Web APIHow to pass json POST data to Web API method as an object?Passing and retrieving complex objects from Angularjs to Web Api

Why does this London Underground poster from 1924 have a Star of David atop a Christmas tree?

Stolen MacBook should I worry about my data?

What to do about my 1-month-old boy peeing through diapers?

Can I get a PhD for developing an educational software?

Shift lens vs move body?

What is the name of this plot that has rows with two connected dots?

Is there any problem with a full installation on a USB drive?

Are strlen optimizations really needed in glibc?

Federal Pacific 200a main panel problem with oversized 100a 2pole breaker

How to force GCC to assume that a floating-point expression is non-negative?

How do solar inverter systems easily add AC power sources together?

Will removing shelving screws from studs damage the studs?

Does NASA use any type of office/groupware software and which is that?

How can I download a file from a host I can only SSH to through another host?

Why is explainability not one of the criteria for publication?

Grep contents before a colon

Why did James Cameron decide to give Alita big eyes?

Could the UK amend the European Withdrawal Act and revoke the Article 50 invocation?

What stops you from using fixed income in developing countries?

Notice period 60 days but I need to join in 45 days

Is this password scheme legit?

Can I use coax outlets for cable modem?

How do we improve collaboration with problematic tester team?

Does the Reduce option from the Enlarge/Reduce spell cause a critical hit to do 2d4 less damage?



Web API not receiving the json of serialized object


HTTP header is being sent, but isn't present in Request.HeadersDeep cloning objectsHow do I format a Microsoft JSON date?ASP.NET Web Site or ASP.NET Web Application?JavaScriptSerializer - JSON serialization of enum as stringDeserialize JSON into C# dynamic object?WCF vs ASP.NET Web APIHow do I get ASP.NET Web API to return JSON instead of XML using Chrome?How to secure an ASP.NET Web APIHow to pass json POST data to Web API method as an object?Passing and retrieving complex objects from Angularjs to Web Api






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















client side code:



 public async Task<ActionResult> Login(UserLoginModel user)

UserModel data = new UserModel

Username = user.Username,
Password = user.Password.GenerateHash()
;

var serializedData = JsonConvert.SerializeObject(data);

var url = "http://localhost:55042/api/Login";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

streamWriter.Write(serializedData);
streamWriter.Flush();
streamWriter.Close();


bool deserializedResult = false;
using (var response = httpWebRequest.GetResponse() as HttpWebResponse)

if (httpWebRequest.HaveResponse && response != null)
using (var streamReader = new StreamReader(response.GetResponseStream()))
var result = streamReader.ReadToEnd();
deserializedResult = JsonConvert.DeserializeObject<bool>(result);




return deserializedResult ? View() : throw new NotImplementedException();



Web API:



 [HttpPost]
[Route("api/Login")]
public IHttpActionResult ValidateLogin([FromBody]UserModel user)

var result = _service.FetchUser(user);

return Json(result);



No data arrives in ValidateLogin, even when I pass parameters with the postman.



I have searched a lot, found no solution at all, tried all the code snippets, understood them then came back and so on, I'm stuck, what is wrong?










share|improve this question
























  • can you provide definition of the UserModel class. From Postman when you send request whats the http status code you recieving back ?

    – Vishnu
    Mar 27 at 20:37











  • @Vishnu 200 OK, UserModel

    – magicalKhachapuri
    Mar 27 at 20:43

















2















client side code:



 public async Task<ActionResult> Login(UserLoginModel user)

UserModel data = new UserModel

Username = user.Username,
Password = user.Password.GenerateHash()
;

var serializedData = JsonConvert.SerializeObject(data);

var url = "http://localhost:55042/api/Login";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

streamWriter.Write(serializedData);
streamWriter.Flush();
streamWriter.Close();


bool deserializedResult = false;
using (var response = httpWebRequest.GetResponse() as HttpWebResponse)

if (httpWebRequest.HaveResponse && response != null)
using (var streamReader = new StreamReader(response.GetResponseStream()))
var result = streamReader.ReadToEnd();
deserializedResult = JsonConvert.DeserializeObject<bool>(result);




return deserializedResult ? View() : throw new NotImplementedException();



Web API:



 [HttpPost]
[Route("api/Login")]
public IHttpActionResult ValidateLogin([FromBody]UserModel user)

var result = _service.FetchUser(user);

return Json(result);



No data arrives in ValidateLogin, even when I pass parameters with the postman.



I have searched a lot, found no solution at all, tried all the code snippets, understood them then came back and so on, I'm stuck, what is wrong?










share|improve this question
























  • can you provide definition of the UserModel class. From Postman when you send request whats the http status code you recieving back ?

    – Vishnu
    Mar 27 at 20:37











  • @Vishnu 200 OK, UserModel

    – magicalKhachapuri
    Mar 27 at 20:43













2












2








2


0






client side code:



 public async Task<ActionResult> Login(UserLoginModel user)

UserModel data = new UserModel

Username = user.Username,
Password = user.Password.GenerateHash()
;

var serializedData = JsonConvert.SerializeObject(data);

var url = "http://localhost:55042/api/Login";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

streamWriter.Write(serializedData);
streamWriter.Flush();
streamWriter.Close();


bool deserializedResult = false;
using (var response = httpWebRequest.GetResponse() as HttpWebResponse)

if (httpWebRequest.HaveResponse && response != null)
using (var streamReader = new StreamReader(response.GetResponseStream()))
var result = streamReader.ReadToEnd();
deserializedResult = JsonConvert.DeserializeObject<bool>(result);




return deserializedResult ? View() : throw new NotImplementedException();



Web API:



 [HttpPost]
[Route("api/Login")]
public IHttpActionResult ValidateLogin([FromBody]UserModel user)

var result = _service.FetchUser(user);

return Json(result);



No data arrives in ValidateLogin, even when I pass parameters with the postman.



I have searched a lot, found no solution at all, tried all the code snippets, understood them then came back and so on, I'm stuck, what is wrong?










share|improve this question














client side code:



 public async Task<ActionResult> Login(UserLoginModel user)

UserModel data = new UserModel

Username = user.Username,
Password = user.Password.GenerateHash()
;

var serializedData = JsonConvert.SerializeObject(data);

var url = "http://localhost:55042/api/Login";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))

streamWriter.Write(serializedData);
streamWriter.Flush();
streamWriter.Close();


bool deserializedResult = false;
using (var response = httpWebRequest.GetResponse() as HttpWebResponse)

if (httpWebRequest.HaveResponse && response != null)
using (var streamReader = new StreamReader(response.GetResponseStream()))
var result = streamReader.ReadToEnd();
deserializedResult = JsonConvert.DeserializeObject<bool>(result);




return deserializedResult ? View() : throw new NotImplementedException();



Web API:



 [HttpPost]
[Route("api/Login")]
public IHttpActionResult ValidateLogin([FromBody]UserModel user)

var result = _service.FetchUser(user);

return Json(result);



No data arrives in ValidateLogin, even when I pass parameters with the postman.



I have searched a lot, found no solution at all, tried all the code snippets, understood them then came back and so on, I'm stuck, what is wrong?







c# asp.net asp.net-mvc asp.net-web-api asp.net-web-api2






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 20:08









magicalKhachapurimagicalKhachapuri

1272 silver badges12 bronze badges




1272 silver badges12 bronze badges















  • can you provide definition of the UserModel class. From Postman when you send request whats the http status code you recieving back ?

    – Vishnu
    Mar 27 at 20:37











  • @Vishnu 200 OK, UserModel

    – magicalKhachapuri
    Mar 27 at 20:43

















  • can you provide definition of the UserModel class. From Postman when you send request whats the http status code you recieving back ?

    – Vishnu
    Mar 27 at 20:37











  • @Vishnu 200 OK, UserModel

    – magicalKhachapuri
    Mar 27 at 20:43
















can you provide definition of the UserModel class. From Postman when you send request whats the http status code you recieving back ?

– Vishnu
Mar 27 at 20:37





can you provide definition of the UserModel class. From Postman when you send request whats the http status code you recieving back ?

– Vishnu
Mar 27 at 20:37













@Vishnu 200 OK, UserModel

– magicalKhachapuri
Mar 27 at 20:43





@Vishnu 200 OK, UserModel

– magicalKhachapuri
Mar 27 at 20:43












1 Answer
1






active

oldest

votes


















4















Solution 1



Just remove [Serializable] attribute from UserModel and everything will work fine.



Solution 2



When serializing data on client use json serialization behavior as Web API does



var serializedData = JsonConvert.SerializeObject(data, new JsonSerializerSettings

ContractResolver = new DefaultContractResolver

IgnoreSerializableAttribute = false

);


Now Web API will correctly deserialize passed model.



This happens because starting from some version Json.NET considers if object is marked as Serializable. By default without that attribute all public members (properties and fields) are serialized. Serialization of the following class



public class UserModel

public string Username get; set;

public string Password get; set;



gives the following result




"Username": "name",
"Password": "pass"



But when class is marked by [Serializable] attribute and IgnoreSerializableAttribute setting is false all private and public fields are serialized and result is the following




"<Username>k__BackingField": "name",
"<Password>k__BackingField": "pass"



By default serializer ignores [Serializable] attribute but in Web API the IgnoreSerializableAttribute is set to false. So now it's easy to see why server couldn't properly deserialize given model in your case.






share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385632%2fweb-api-not-receiving-the-json-of-serialized-object%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4















    Solution 1



    Just remove [Serializable] attribute from UserModel and everything will work fine.



    Solution 2



    When serializing data on client use json serialization behavior as Web API does



    var serializedData = JsonConvert.SerializeObject(data, new JsonSerializerSettings

    ContractResolver = new DefaultContractResolver

    IgnoreSerializableAttribute = false

    );


    Now Web API will correctly deserialize passed model.



    This happens because starting from some version Json.NET considers if object is marked as Serializable. By default without that attribute all public members (properties and fields) are serialized. Serialization of the following class



    public class UserModel

    public string Username get; set;

    public string Password get; set;



    gives the following result




    "Username": "name",
    "Password": "pass"



    But when class is marked by [Serializable] attribute and IgnoreSerializableAttribute setting is false all private and public fields are serialized and result is the following




    "<Username>k__BackingField": "name",
    "<Password>k__BackingField": "pass"



    By default serializer ignores [Serializable] attribute but in Web API the IgnoreSerializableAttribute is set to false. So now it's easy to see why server couldn't properly deserialize given model in your case.






    share|improve this answer































      4















      Solution 1



      Just remove [Serializable] attribute from UserModel and everything will work fine.



      Solution 2



      When serializing data on client use json serialization behavior as Web API does



      var serializedData = JsonConvert.SerializeObject(data, new JsonSerializerSettings

      ContractResolver = new DefaultContractResolver

      IgnoreSerializableAttribute = false

      );


      Now Web API will correctly deserialize passed model.



      This happens because starting from some version Json.NET considers if object is marked as Serializable. By default without that attribute all public members (properties and fields) are serialized. Serialization of the following class



      public class UserModel

      public string Username get; set;

      public string Password get; set;



      gives the following result




      "Username": "name",
      "Password": "pass"



      But when class is marked by [Serializable] attribute and IgnoreSerializableAttribute setting is false all private and public fields are serialized and result is the following




      "<Username>k__BackingField": "name",
      "<Password>k__BackingField": "pass"



      By default serializer ignores [Serializable] attribute but in Web API the IgnoreSerializableAttribute is set to false. So now it's easy to see why server couldn't properly deserialize given model in your case.






      share|improve this answer





























        4














        4










        4









        Solution 1



        Just remove [Serializable] attribute from UserModel and everything will work fine.



        Solution 2



        When serializing data on client use json serialization behavior as Web API does



        var serializedData = JsonConvert.SerializeObject(data, new JsonSerializerSettings

        ContractResolver = new DefaultContractResolver

        IgnoreSerializableAttribute = false

        );


        Now Web API will correctly deserialize passed model.



        This happens because starting from some version Json.NET considers if object is marked as Serializable. By default without that attribute all public members (properties and fields) are serialized. Serialization of the following class



        public class UserModel

        public string Username get; set;

        public string Password get; set;



        gives the following result




        "Username": "name",
        "Password": "pass"



        But when class is marked by [Serializable] attribute and IgnoreSerializableAttribute setting is false all private and public fields are serialized and result is the following




        "<Username>k__BackingField": "name",
        "<Password>k__BackingField": "pass"



        By default serializer ignores [Serializable] attribute but in Web API the IgnoreSerializableAttribute is set to false. So now it's easy to see why server couldn't properly deserialize given model in your case.






        share|improve this answer















        Solution 1



        Just remove [Serializable] attribute from UserModel and everything will work fine.



        Solution 2



        When serializing data on client use json serialization behavior as Web API does



        var serializedData = JsonConvert.SerializeObject(data, new JsonSerializerSettings

        ContractResolver = new DefaultContractResolver

        IgnoreSerializableAttribute = false

        );


        Now Web API will correctly deserialize passed model.



        This happens because starting from some version Json.NET considers if object is marked as Serializable. By default without that attribute all public members (properties and fields) are serialized. Serialization of the following class



        public class UserModel

        public string Username get; set;

        public string Password get; set;



        gives the following result




        "Username": "name",
        "Password": "pass"



        But when class is marked by [Serializable] attribute and IgnoreSerializableAttribute setting is false all private and public fields are serialized and result is the following




        "<Username>k__BackingField": "name",
        "<Password>k__BackingField": "pass"



        By default serializer ignores [Serializable] attribute but in Web API the IgnoreSerializableAttribute is set to false. So now it's easy to see why server couldn't properly deserialize given model in your case.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 27 at 22:04

























        answered Mar 27 at 21:16









        AlexanderAlexander

        3,8471 gold badge5 silver badges21 bronze badges




        3,8471 gold badge5 silver badges21 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55385632%2fweb-api-not-receiving-the-json-of-serialized-object%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript