:
public int Post(MyModel m){
return CreateTask(m);
}返回值:
Id:"<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1446</int>"我的问题是:为什么web会像上面那样返回Id。我需要它作为"1446".How,我可以去掉这个xml部分吗?
发布于 2014-09-30 21:11:41
WebApi项目是在Global.asax中配置的;在那里您可以找到一个名为WebApiConfig的类。在这个类中,您可以找到"Media format “;Media说明您的WebApi是否能够序列化/反序列化JSON、System.Net.Http.Formatting.JsonMediaTypeFormatter()或任何其他格式。
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());
}
}如果JSON格式化程序是列表中的第一项,那么它将是默认的序列化程序/反序列化程序,为了访问任何其他格式,请求的内容类型应该显式地指示所需的格式,如果支持它,它将返回它,如果不是,它将以默认格式返回它。
您所看到的输出的结果完全是所选媒体格式化程序所使用的反序列化/序列化的责任。
发布于 2014-09-30 21:31:45
如果您只想返回1446,您需要返回一个HttpResponseMessage,如下所示:
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;
}如果全局更改配置,则在实现需要返回其他格式的web服务时,可能会导致问题。通过返回一个HttpResponseMessage,您只需担心正在处理的特定方法。
发布于 2014-09-30 21:11:36
在您的请求中,将Accept标头设置为application/json:
Accept: application/jsonhttps://stackoverflow.com/questions/26130128
复制相似问题