将对象发布到json中的wcf rest服务返回名称空间错误

时间:2017-05-28 14:11:02

标签: c# json rest

我正在尝试使用wcf-rest服务向我的数据库添加news对象,如您所见:

Guid id;
id = Guid.NewGuid();

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:47026/NewsRepository.svc/AddNews");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "PUT";

JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};

string json = JsonConvert.SerializeObject(new
{
    Id = id,
    Subject = "wfwf",
    ViewerCounter = "1",
    Content = "fsdsd",
    SubmitDateTime = "2012/12/12",
    ModifiedDateTime = "2012/12/12",
    PublisherName = "sdaadasd",
    PictureAddress = "adfafsd",
    TypeOfNews = "adsadaad"

}, microsoftDateFormatSettings);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(streamWriter, json);
}
try { 

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}
}
catch(Exception er)
{
    MessageBox.Show(er.ToString());
}

但是它返回了错误的请求400.所以我跟踪了WCF日志中的错误,我发现了这个:

Expecting state 'Element'.. Encountered 'Text'  with name '', namespace ''. 

这是我的服务代码:

 [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "/AddNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    bool Add(News entity);

并且

 public class NewsRepository :INewsRepository
    {
        private readonly DataContext _ctx;
        public NewsRepository(DataContext ctx)
        {
            _ctx = ctx;
        }

        public bool Add(News entity)
        {
            try
            {
                _ctx.News.Add(entity);
                _ctx.SaveChanges();
                return true;
            }

我的新闻模式

[DataContract]
public class News
{
    [DataMember]

    public Guid Id { set; get; }
    [DataMember]

    public string Subject { set; get; }
    [DataMember]

    public int ViewerCounter { set; get; }
    [DataMember]

    public string MainContent { set; get; }
    [DataMember]

    public DateTime SubmitDateTime { set; get; }
    [DataMember]

    public DateTime ModifiedDateTime { set; get; }
    [DataMember]

    public string PublisherName { set; get; }
    [DataMember]

    public string PictureAddress { set; get; }
    [DataMember]

    public string TypeOfNews { set; get; }//etelaeie ya khabar



}

更改了代码

 Guid id;
            id = Guid.NewGuid();

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:47026/NewsRepository.svc/AddNews");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
            };

            string json = JsonConvert.SerializeObject(new News()
            {
                Id = id,
                Subject = "wfwf",
                ViewerCounter = 1, // removed the "" (string)
                MainContent = "fsdsd", // renamed from "Content"
                SubmitDateTime = DateTime.Now,
                ModifiedDateTime = DateTime.Now,
                PublisherName = "sdaadasd",
                PictureAddress = "adfafsd",
                TypeOfNews = "adsadaad"
            }, microsoftDateFormatSettings);

            using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(streamWriter, json);
            }
            try { 
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }
            }
            catch(Exception er)
            {
                MessageBox.Show(er.ToString());
            }

但同样的错误

2 个答案:

答案 0 :(得分:0)

类型不匹配

目前您的匿名类型具有以下属性

public Guid Id { get; set; }
public string Subject { get; set; }
public string ViewerCounter { get; set; }
public string Content { get; set; }
public DateTime SubmitDateTime { get; set; }
public DateTime ModifiedDateTime { get; set; }
public string PublisherName { get; set; }
public string PictureAddress { get; set; }
public string TypeOfNews  { get; set; }

与您预期的News

类型不符
public class News
{
    public Guid Id { set; get; }
    public string Subject { set; get; }
    public int ViewerCounter { set; get; }
    public string MainContent { set; get; }
    public DateTime SubmitDateTime { set; get; }
    public DateTime ModifiedDateTime { set; get; }
    public string PublisherName { set; get; }
    public string PictureAddress { set; get; }
    public string TypeOfNews { set; get; }
}

快速修复

string json = JsonConvert.SerializeObject(new
{
    Id = id,
    Subject = "wfwf",
    ViewerCounter = 1, // removed the "" (string)
    MainContent = "fsdsd", // renamed from "Content"
    SubmitDateTime = "2012/12/12",
    ModifiedDateTime = "2012/12/12",
    PublisherName = "sdaadasd",
    PictureAddress = "adfafsd",
    TypeOfNews = "adsadaad"
}, microsoftDateFormatSettings);

建议

为了使代码更易于管理,您应确保尽可能发送相同类型的代码(在本例中为News)。目前您正在向服务发送匿名类型,这可能是您问题的罪魁祸首......

所以你应该从改变

开始
string json = JsonConvert.SerializeObject(new { ... }); // anonymous type

string json = JsonConvert.SerializeObject(new News { ... }); // News type

答案 1 :(得分:0)

最终解决方案:

   News student = new News
            {
                Id = Guid.NewGuid(),
                Subject = "wfwf",
                ViewerCounter = 1, // removed the "" (string)
                MainContent = "fsdsd", // renamed from "Content"
                SubmitDateTime = DateTime.Now,
                ModifiedDateTime = DateTime.Now,
                PublisherName = "sdaadasd",
                PictureAddress = "adfafsd",
                TypeOfNews = "adsadaad"
            };
            WebClient Proxy1 = new WebClient();
            Proxy1.Headers["Content-type"] = "application/json";
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(News));
            serializerToUplaod.WriteObject(ms, student);
             Proxy1.UploadData("http://localhost:47026/NewsRepository.svc/AddNews", "POST", ms.ToArray());