RESTful Web服务+ JSON + SQL存储过程项目的问题 [英] Issue with RESTful webservice +JSON+SQL stored procedure project

查看:61
本文介绍了RESTful Web服务+ JSON + SQL存储过程项目的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我确实想念一些东西.我的整个项目有点像是复制和粘贴各种如何...",我对C#的知识充其量只是基础知识,因为我们的标准Web服务软件仅在发送时才是RESTful,所以我需要使C#正常工作.

I know for a fact that there is something I miss. My whole project is somewhat copy&paste of various "how to..."s, my knowledge of C# is basic at best and I need to have it working since our standard web service software is RESTful only when sending.

我的主要问题是,我偶然发现的所有解决方案实际上都是代码段,这些代码段对我不起作用-我的C#知识是基础知识,因此我不了解它们的全部工作原理,更不用说对其进行故障排除了.我很确定我什至没有捕获传入请求中发布的JSON.但是太太,我可能错了.

My main problem is that all solutions I've stumbled upon are actually code snippets, which don't work for me - my C# knowledge is basic so I don't understand how it all works, much less troubleshoot it. I'm pretty sure I'm not even capturing the JSON that's being posted with incoming request. But OTOH I may be wrong.

需求:可以在WS2012R2上的IIS上运行的东西,可以通过HTTPPost接受JSON文件,将内容转储到SQL Server表中,并将刚创建的行的ID返回给JSON的发送者.我将不得不在此基础上构建完善的Web服务,该服务可以发送和接收包含不同数据的多个JSON文件,所有这些文件都必须最终存储在SQL Server中.

Requirement: something that works off IIS on WS2012R2, can accept JSON files via HTTPPost, dump content into a SQL Server table and return Id for the row that just was created to the sender of the JSON. I will have to build on it to get full-blown web service that sends and receives multiple JSON files containing different data, all have to end up in SQL Server.

我所拥有的:

班级:

    namespace NA.Models
{
    public class Note
    {
        public Note() { }

        //public Guid id { get; set; }
        public static string Client { get; set; }
        public static int Case { get; set; }
        public static string Text { get; set; }
        public static int NoteId { get; set; }
        public static string R1 { get; set; }
        public static string R2 { get; set; }
        public static string S1 { get; set; }
        public static DateTime Date { get; set; }
        public static bool Type { get; set; }
      }
    }

界面:

    namespace NA.Models
{
    interface INoteRepository
    {
        IEnumerable<Note> GetAll();
        void Add(Note item);
    }
}

存储库:

namespace NA.Models
{
  class NoteDataRepository : INoteRepository
  {
     public void Add(Note item)
     {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }
        else
        {
            String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "BL_IntegrationInsertNote";
            cmd.Parameters.Add("@Client", SqlDbType.VarChar).Value = item.Client.Trim();
            cmd.Parameters.Add("@Case", SqlDbType.VarChar).Value = item.case;
            cmd.Parameters.Add("@Text", SqlDbType.VarChar).Value = item.Text.Trim();
            cmd.Parameters.Add("@When", SqlDbType.DateTime).Value = item.Date;
            cmd.Parameters.Add("@Ext", SqlDbType.Bit).Value = item.Type;
            cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.Output;
            cmd.Connection = con;

            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                string id = cmd.Parameters["@return"].Value.ToString();
                string lblMessage = null;
                lblMessage = "Record inserted successfully. ID = " + id;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }    
        return item;
    }

    IEnumerable<Note> INoteRepository.GetAll()
    {
        throw new NotImplementedException("getitems");
    }
}
}

控制器:

namespace NA.Controllers
{
   public class NC : ApiController
   {
      [Route("AddNote")]
      [HttpPost]
    public HttpResponseMessage PostNote(List<Note> item)
    {
        //NoteJson deserializednote = JsonConvert.DeserializeObject<NoteJson>(item);
        //Note notesdata = new Note(item);
        //foreach (deserializednote   
        NotesAccept.Models.INoteRepository Repository = new NotesAccept.Models.NoteDataRepository();
        item = Repository.Add(item);
        var response = Request.CreateResponse < NotesAccept.Models.Note>(HttpStatusCode.Created, item);

        return response;
    }
   }
}

当尝试将测试json发送到服务时,我得到一个错误提示:

When trying to send test json to the service I get an error in return:

500:内部服务器错误,参数项的值不能为空

500: Internal server error, Value cannot be null at Parameter item

这是已发送的请求的posttestserver.com转储:

This is posttestserver.com dump of request sent:

Headers (Some may be inserted by server)
REQUEST_URI = /post.php
QUERY_STRING = 
REQUEST_METHOD = POST
GATEWAY_INTERFACE = CGI/1.1
REMOTE_PORT = 56926
REMOTE_ADDR = ip
HTTP_CONNECTION = close
HTTP_CACHE_CONTROL = max-age=259200
HTTP_X_FORWARDED_FOR = 172.16.3.87
HTTP_VIA = 1.1 koenig.local (squid/3.3.13)
HTTP_EXPECT = 100-continue
CONTENT_LENGTH = 153
HTTP_HOST = posttestserver.com
HTTP_ACCEPT = application/json
CONTENT_TYPE = application/json
UNIQUE_ID = Vri0cUBaMGUAABvGeesAAAAL
REQUEST_TIME_FLOAT = 1454945393.4611
REQUEST_TIME = 1454945393

No Post Params.

== Begin post body ==
[{
    "Client": "Client1",
    "Case": 1,
    "Text": "Text",
    "NoteId": 2,
    "R1": "R1",
    "R2": "R2",
    "S1": "S1",
    "Date": "2015-10-26T09:06:46",
    "Type":"1"
}]
== End post body ==

Upload contains PUT data:
[{
    "Client": "Client1",
    "Case": 1,
    "Text": "Text",
    "NoteId": 2,
    "R1": "R1",
    "R2": "R2",
    "S1": "S1",
    "Date": "2015-10-26T09:06:46",
    "Type":"1"
}]

以上转储来自POST请求,该请求与我发送到Web服务的请求相同,但URL除外.因此可以视为实际要求. 这是一个IIS日志:

The above dump is from POST request which is identical to one I'm sending to my web service, with exception of URL. So can be treated as actual request. And here is an IIS log:

字段:日期时间s-ip cs方法cs-uri-stem cs-uri-query s-port cs-用户名c-ip cs(User-Agent)cs(Referer)sc-状态sc-substatus sc-win32-status花费的时间2016-02-08 15:49:52 :: 1 POST/blz/AddNote- 80-:: 1--500 0 0 2937

Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken 2016-02-08 15:49:52 ::1 POST /blz/AddNote - 80 - ::1 - - 500 0 0 2937

推荐答案

确定,因此您需要更改一些内容才能使其正常工作:

OK, so there are several things that you need to change to make it working:

  1. 将非参数构造函数添加到Note中,因为反序列化将需要它:

  1. Add parameterless constructor to Note as it will be needed for deserialization:

public Note()
{
}

  • 在注释"字段中摆脱静态":

  • Get rid of "static" in Note's fields:

    公共静态字符串客户{放; }

    public static string Client { get; set; }

    public static int Case {get;放; }

    public static int Case { get; set; }

    公共静态字符串文本{get;放; }

    public static string Text { get; set; }

    public static int NoteId {get;放; }

    public static int NoteId { get; set; }

    公共静态字符串R1 {get;放; }

    public static string R1 { get; set; }

    公共静态字符串R2 {get;放; }

    public static string R2 { get; set; }

    公共静态字符串S1 {get;放; }

    public static string S1 { get; set; }

    公共静态 DateTime日期{放; }

    public static DateTime Date { get; set; }

    public 静态 bool类型{get;放; }

    public static bool Type { get; set; }

    如果只需要1个对象,则不发送JSON数组,它不会反序列化.您期望的是单个对象,而不是数组,所以不要发送数组.

    Don't send JSON array if you want just 1 object, it won't deserialize. You are expecting single object, not array, so don't send array.

    您具有Type作为bool,但是您正在发送字符串"1",这不会像您期望的那样反序列化为真实值.发送true/false(不是"true"/"false")或将Type的类型更改为字符串.

    You have Type as bool, but you are sending string "1", this will not deserialize to true value as you might expected. Either send true/false (not "true"/"false") or change type of Type to string.

    摆脱该私人物品字段,您不需要它:

    Get rid of that private item field, you don't need it:

    私人注释项;

    摆脱那里的那些构造函数

    Get rid of those constructors that you have there

    公共注释(字符串json)

    公共注释(注释项)

    不仅它们没有意义并且不起作用,您也不需要它们,因为JSON反序列化器将为您填充字段.

    Not only that they make no sense and won't work, you don't need them as JSON deserializer will fill the fields for you.

    例如,您说它不会生成,因为不再有带有一个参数的构造函数.当然它不会建立,有这行

    For example, you say it does not build because there is no more a constructor with one parameter. Of course it does not build, there is this line

    Note notesdata = new Note(item);
    

    但是您不需要该行.这条线背后的想法是什么?您需要Note类的实例,但是已经在"item"变量中拥有它.您不需要创建第二个副本.所以也要摆脱它.

    but you do not need that line. What is the idea behind this line? You want an instance of Note class, but you already have it in "item" variable. You do not need to create a second copy of that. So get rid of this too.

    无法编译的另一个原因是,您摆脱了这些静态字段,而在Add方法中仍然保留了这些静态字段:

    Another reason, why it won't compile is that you get rid of those static fields, while you still have this in your Add method:

            cmd.Parameters.Add("@Text", SqlDbType.VarChar).Value = Note.Text.Trim();
            cmd.Parameters.Add("@When", SqlDbType.DateTime).Value = Note.Date;
    

    我很确定你不想要那样.相反,您想使用发送给您的对象的实例:

    and I am quite sure you do not want that. Instead, you want to use the instance of the object that were sent to you:

            cmd.Parameters.Add("@Text", SqlDbType.VarChar).Value = item.Text.Trim();
            cmd.Parameters.Add("@When", SqlDbType.DateTime).Value = item.Date;
    

    另一件事是,通常没有理由为什么Add方法将要添加的对象返回到DB.所以随时更改

    Another thing is that there is usually no reason why would Add method return the object being added to DB. So feel free to change this

       public Note Add(Note item)
    

    对此

       public void Add(Note item)
    

    不返回任何东西,您不需要它.

    and do not return anything, you do not need it.

    我不是SqlConnection及其周围事物的专家,因此我不对此部分进行评论.我在我的项目中使用EF来处理DB.因此,该部分可能存在一些问题,但我对此无法发表评论.

    I am no expert on SqlConnection and things around it, so that part I do not comment. I use EF in my projects for working with DB. So there might be some problems in that part, but I can't comment on that.

    这篇关于RESTful Web服务+ JSON + SQL存储过程项目的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆