c# - 在处理请求之前如何用asp读取json post的内容?

标签 c# asp.net web-services iis

我想做的在 php 中非常简单。我只是想阅读帖子的内容。它在 sailsjs/node 上也非常简单......我只是从异步函数中返回结果。

在 c# asp 中,我找不到答案。我希望函数在尝试处理帖子之前读取帖子的内容。

有时下面的代码可以工作。有时从帖子中读取 json 的速度太慢,jsonText 被读取为“”,因此没有任何处理。

在所有测试运行中,json 都在帖子正文中发送。

在确保先阅读帖子内容后返回 httpResponse 的最佳方式是什么?

public HttpResponseMessage Post()
    {
        string content;
        try
        {
            string result = String.Empty;
            Newtonsoft.Json.Linq.JObject jObject = null;

            string jsonText = String.Empty;
            var syncTask = new Task<string>( () =>  {
                  return Request.Content.ReadAsStringAsync().Result;
            });
            /* I'm expecting that this will finish */ 
            syncTask.RunSynchronously();
            jsonText = syncTask.Result;

            /* before this line of code executes */
            System.Net.Http.HttpResponseMessage response = new HttpResponseMessage();

            if (jsonText == "")
            {
                result = "{\"error\":\"body is empty\"}";
                response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
            }
            else
            {
                jObject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JRaw.Parse(jsonText);

                string ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                jObject["ipAddress"] = ipAddress;

                Models.JsonXML jsonXml = new JsonXML(jObject.ToString(Newtonsoft.Json.Formatting.None));
                System.Xml.XmlDocument document = new System.Xml.XmlDocument();
                document.LoadXml(jsonXml.xml);
                result = ReferralsManager.ProcessReferral(document);
                if (result == "")
                {
                    result = "{}";
                }

                response.StatusCode = System.Net.HttpStatusCode.OK;
            }
            response.Content = new StringContent(result);
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            return response;
        }
        catch (Exception ex)
        {
            content = ErrorMessage.ServerException(Converter, ex);
            return Request.ToResponseMessage(content);
        }
        finally
        {
            LogManager.GetCurrentClassLogger().Info(InfoMessage.FUNC_ENDS, "Process Referral");
        }
    }

@Mekap 回答后的工作修改代码是

    public class ProcessReferralAddressModel {

        public ProcessReferralAddressModel() { }

        public string address { get; set; }
        public string name { get; set; }

    }

    public class ProcessReferralModel
    {
        public ProcessReferralModel()
        {

        }
        public string uuid { get; set; }
        public DateTime date { get; set; }
        public ProcessReferralAddressModel from { get; set; }
        public ProcessReferralAddressModel[] to { get; set; }
        public string subject { get; set; }
        public string text { get; set; }
        public string html { get; set; }

    }

    /// <summary>
    /// Process a referral.
    /// </summary>
    /// <param name="userid">The userid.</param>
    /// <returns></returns>
    public HttpResponseMessage Post([FromBody] ProcessReferralModel processReferralModel)
    {
        string content;
        string jsonText = Newtonsoft.Json.JsonConvert.SerializeObject(processReferralModel) ;

        try
        {
            string result = String.Empty;
            Newtonsoft.Json.Linq.JObject jObject = null;


            System.Net.Http.HttpResponseMessage response = new HttpResponseMessage();

            if (jsonText == "" || jsonText == null )
            {
                result = "{\"error\":\"body is empty\"}";
                response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
            }
            else
            {
                jObject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JRaw.Parse(jsonText);

                string ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                jObject["ipAddress"] = ipAddress;

                Models.JsonXML jsonXml = new JsonXML(jObject.ToString(Newtonsoft.Json.Formatting.None));
                System.Xml.XmlDocument document = new System.Xml.XmlDocument();
                document.LoadXml(jsonXml.xml);
                result = ReferralsManager.ProcessReferral(document);
                if (result == "")
                {
                    result = "{}";
                }

                response.StatusCode = System.Net.HttpStatusCode.OK;
            }
            response.Content = new StringContent(result);
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            return response;
        }
        catch (Exception ex)
        {
            content = ErrorMessage.ServerException(Converter, ex);
            return Request.ToResponseMessage(content);
        }
        finally
        {
            LogManager.GetCurrentClassLogger().Info(InfoMessage.FUNC_ENDS, "Process Referral");
        }
    }

最佳答案

你正在获取的 json,对于我们的示例来说,它看起来像

{ "ID" : 3,
 "StringCmd" : "ls -l"
}

对于初学者,我们将编写一个小类,在您的 web api 中表示我们的数据

public class StringCmdModel
{
    public StringCmdModel()
    {
    }
    public int ID { get; set; }
    public string StringCmd { get; set; }
}

现在,我们只需要在我们的 WebAPI 中编写我们的入口点:

 [HttpPost]
 public HttpResponseMessage PostFonction([FromBody] StringCmdModel NewEntry)

您不必检查函数内的数据是否存在。但是您仍然应该对它们的值进行适当的检查,以防您收到格式错误的 json 或恶意调用。

但是,如果您收到的 json 调用与您在正文中提供的参数中的 StringCmdModel 不匹配,则该函数将不会执行,并且服务器将自行抛出一个 500错误。

关于c# - 在处理请求之前如何用asp读取json post的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37990610/

相关文章:

c# - 使用 C# 在 HTML 中查找特定类并获取其值

java - WSDL 警告 : not a SOAP port, 它没有 SOAP :地址

c# - 在 C# 中寻找可用的不可变 bool 数组

c# - 将 string[][] 转换为 int[][]

c# - wpf 附加属性 : where to unsubscribe from event handling?

c# - ManagementObjectSearcher Get() 方法抛出异常

asp.net - Jquery UI 选项卡中止不起作用

jquery - 如何通过 jQuery 设置 'code behind' 属性

java - Java Web 应用程序中的地理围栏

java - Web服务与java android