【问题标题】:MVC can not get JSON from request Post "x-form-urlencoded"MVC 无法从请求帖子“x-form-urlencoded”中获取 JSON
【发布时间】:2023-04-07 14:34:01
【问题描述】:

我尝试从 body 中获取 JSON,但总是得到 null。

这是我在 MVC 中的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using System.Web.Http;
using System.Net.Http;
using System.Net;
using System.IO;

namespace WebApplication5.Controllers
{
    public class NimsoftController : Controller
    {
        static readonly Dictionary<Guid, Alert> alerts = new Dictionary<Guid, Alert>();

        // GET: Nimsoft
        //public ActionResult CreateAlarm()
        [System.Web.Mvc.HttpPost]
        public HttpResponseMessage CreateAlarm([FromBody] Alert val)
        {
            Models.CreateAlarm CreateAlarm = new Models.CreateAlarm();
            System.IO.File.AppendAllText(@"D:\log.txt", string.Join(",", val.message));
            string jsonAlarm = new JavaScriptSerializer().Serialize(new
            {
               message = "Test Message"//string.Join(",",alert.alerts),
            });

            var response = new HttpResponseMessage(HttpStatusCode.Created)
            {
                Content = new StringContent(jsonAlarm)
            };

            return response;
        }
    }
}

还有我的要求

User-Agent: Fiddler
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-type: application/x-www-form-urlencoded
Host: localhost:52151
Content-Length: 27 '

【问题讨论】:

标签: c# asp.net asp.net-mvc-4 asp.net-web-api


【解决方案1】:

您应该将StringContentmediaType参数设置为application/json

Content = new StringContent(jsonAlarm, Encoding.UTF8, "application/json");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2020-10-20
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    相关资源
    最近更新 更多