简体   繁体   中英

Web API returns XML content

Web API :

 public int Post(MyModel m){
    return CreateTask(m);
 }

Return value :

Id:"<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1446</int>"

My question : Why web API returns Id as above.I need it as "1446".How can I get rid of this xml part ?

WebApi project is configured in the Global.asax; it is there where you will find a class named WebApiConfig . Inside this class you will find the " Media Formatters "; the Media Formatters says whether or not your WebApi is capable of serialize/deserialize JSON System.Net.Http.Formatting.JsonMediaTypeFormatter() , XML or any other format.

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
           //...

            System.Web.Http.GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            config.Formatters.Insert(0, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
            config.Formatters.Insert(0, new System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter());


        }
    }

If the JSON formatter is the first item in your list it will be your default serializer/deserializer in order to access any other format the content type of the request should explicitly indicate the desired format if it is supported it will return it and if not it will return it in the default format.

The result of the output you are seeing is entirely responsibility of the deserialization/serialization that the selected media formatter is using.

If you want to return just 1446 you need to return an HttpResponseMessage , like this:

public HttpResponseMessage Post(Event_model event)
{

HttpResponseMessage TheHTTPResponse = new HttpResponseMessage();
TheHTTPResponse.StatusCode = System.Net.HttpStatusCode.OK;
TheHTTPResponse.Content = new StringContent(Event.CreateEvent(event).ToString(), Encoding.UTF8, "text");

return TheHTTPResponse;

}

If you change the configuration globally then it might cause problems when you implement a web service that needs to return some other format. By returning an HttpResponseMessage you can just worry about the particular method you're dealing with.

在您的请求中,将Accept标头设置为application / json:

Accept: application/json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM