Post object to a wcf rest service in json returns

2019-08-22 10:21发布

I am trying to add a news object to my database using wcf-rest service as you can see:

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());
}

But it returns bad request 400 .so I traced the error in WCF log and I found this:

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

here is my service code :

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

And

 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;
            }

And my news model

[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



}

Changed code

 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());
            }

But same error

标签: c# json rest
2条回答
Bombasti
2楼-- · 2019-08-22 10:50

Final solution :

   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());
查看更多
别忘想泡老子
3楼-- · 2019-08-22 11:09

Mismatched types

At the moment your anonymous type has the following properties

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; }

Which does not match your expected type of 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; }
}

Quick Fix

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);

Suggestion

To make your code easier to manage, you should make sure that you are sending across the same type whenever possible (in this case News). At the moment you are sending an anonymous type to the service, which may be the culprit to your issue...

So you should start off with changing

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

to

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

查看更多
登录 后发表回答