【问题标题】:How to read post data in API Controller - MVC4如何在 API 控制器中读取发布数据 - MVC4
【发布时间】:2017-05-19 12:29:54
【问题描述】:

我在 Visual Studio 2010 中使用向导创建了 API 控制器。

它创建了这个函数:

    // POST api/Default1
    public HttpResponseMessage PostUserProfile(UserProfile userprofile)
    {
        System.Diagnostics.Debug.WriteLine("Username: " + userprofile.UserName);
        if (ModelState.IsValid)
        {
            db.UserProfiles.Add(userprofile);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, userprofile);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = userprofile.UserId }));
            return response;
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

我无法添加 [HttpPost] 注释,因为我猜 MVC 4 使用较旧的 API。我还得到参数 userprofile 的 NullPointerException,这意味着它的数据类型错误。我的 PostUserProfile() 函数的 send as 参数应该如何更改以及如何更改? 应该是 Json 对象还是我不知道是什么?

【问题讨论】:

    标签: asp.net-mvc rest asp.net-mvc-4 model-view-controller


    【解决方案1】:

    1- 你的 web api 操作应该是这样的。

            [HttpPost]           
            public HttpResponseMessage PostUserProfile(HttpRequestMessage request, UserProfile userprofile)
            {
                 // code here
            }
    

    2 - 您必须使用 System.Web.Http 而不是 System.Web.MVC 才能使 HttpPost 工作。

    3-您需要在客户端将您的 javascript 数据序列化为 JSON,asp.net 运行时将自动将其反序列化为 UserProfile 对象,前提是您的 Javascript 对象与 UserProfile c# 对象具有相同的属性名称

    【讨论】:

    • 感谢您指出包含错误的软件包。有效。我还必须提到,从 Ajax 调用发送的数据必须是 json 类型,并且必须是字符串,即使用 JSON.stringify({data object})
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2013-07-03
    • 2018-01-20
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多