【问题标题】:How to input a JSON object as a parameter into Controller methods in C#如何将 JSON 对象作为参数输入到 C# 中的控制器方法中
【发布时间】:2016-08-17 07:23:46
【问题描述】:

下面是我的控制器类:

using Pay.Models;
using System.Web.Http;
using Pay.General;

namespace Pay.Controllers
{
    [RoutePrefix("Account")]
    public class AccountsController : ApiController     
    {

        [Route("Login")]
        [HttpPost]   
        public UserSession Login([FromBody]LoginUser loginUser)
        {
            if (loginUser.email != null && loginUser.password !=null && loginUser.token !=null) { }
            byte[] mSessionID = new Session().getmSessionID();
            return new UserSession
            {
                SessionID = mSessionID
            };
        }
    }
}

Model类LoginUser是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Pay.Models
{
    public class LoginUser
    {
        public string email { get; set; }
        public string password { get; set; }
        public byte[] token { get; set; }
    }
}

但是当我调用 Login 函数时,LoginUser 对象被设置为 null。 请告知如何将 JSON 对象设置为 Controller 类。

【问题讨论】:

  • 尝试将 FromBody 更改为 FromURI
  • 你能分享你的调用方法吗?
  • 参考这个链接可能对你有帮助stackoverflow.com/questions/5022958/…
  • 我能够将 JSON 对象中的值输入到模型类(LoginUSer.java)中,除了 Token.. Token 保持为空,其他两个值都映射到 LoginUSer 类
  • 我的同事研究得很好,她找到了合适的链接。

标签: c# json controller


【解决方案1】:

我得到了同事的帮助,她找到了正确的链接。

https://weblog.west-wind.com/posts/2013/dec/13/accepting-raw-request-body-content-with-aspnet-web-api....

我为解决此问题所做的代码更改是

公共异步任务登录() { 字符串输入 = 等待 Request.Content.ReadAsStringAsync();动态数据 = Newtonsoft.Json.Linq.JObject.Parse(input); }

(输入 - 返回为 JSON 格式的字符串) (数据 - 返回 JSON 对象)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2016-12-27
    • 2011-10-19
    相关资源
    最近更新 更多