【发布时间】:2012-04-02 10:28:19
【问题描述】:
我有一个请求外部网络服务并在此处返回 json 的方法:
public string GetJsonRequest(string url)
{
string response = string.Empty;
var request = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (request != null)
{
request.Method = WebRequestMethods.Http.Get;
request.Timeout = 20000;
request.ContentType = "application/json";
var httpresponse = (HttpWebResponse)request.GetResponse();
using (var streamreader = new StreamReader(httpresponse.GetResponseStream()))
response = streamreader.ReadToEnd();
if (httpresponse != null) httpresponse.Close();
}
return response;
}
还有一个在这里返回结果的方法:
public JsonResult Makes()
{
CarRepository rep = new CarRepository();
return new JsonResult()
{
Data = rep.GetMakes(),
ContentType = "application/json"
};
}
或
public string Makes()
{
CarRepository rep = new CarRepository();
return rep.GetMakes();
}
这会返回正确的 json,但它是用 XML 包装的
<JsonResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ContentType>application/json</ContentType>
<Data xsi:type="xsd:string">
The JSON data.......
</Data>
<JsonRequestBehavior>AllowGet</JsonRequestBehavior>
<MaxJsonLength xsi:nil="true"/>
<RecursionLimit xsi:nil="true"/>
</JsonResult>
我已经检查了提琴手中的请求,并且 Accept 标头中只有 xml 值。我怎样才能让它只打印出 json?我正在使用 ASP.NET Web API。我可以在应用程序启动时删除 XML mediatypeformatter,但我可能需要稍后使用它,所以我不认为这是要走的路。
提前致谢
【问题讨论】:
标签: xml asp.net-mvc json asp.net-mvc-4 asp.net-web-api