问题描述
我正在使用ApiController,但无法获得返回XML以外的任何内容的呼叫.
I'm using ApiController and I can't get the call to return anything other than XML.
public class GuideController : ApiController
{
[AcceptVerbs("GET")]
[HttpGet]
public string Get()
{
Item item = Item.GetTestData();
string json = JsonConvert.SerializeObject(item);
return json;
}
}
理想情况下,我想正常返回JSON,但我愿意返回原始字符串,而不是XML包装的字符串.
Ideally, I want to return JSON normally but I'd settle for returning raw strings instead of XML wrapped ones.
推荐答案
确保api仅返回JSON的简单方法是从http配置中删除xml格式化程序.
An easy way to make sure the api only returns JSON is to remove the xml formatter from the http configuration.
您可以在WebApiConfig类中访问格式化程序
You can access the formatters in the WebApiConfig class
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//Clear current formatters
config.Formatters.Clear();
//Add only a json formatter
config.Formatters.Add(new JsonMediaTypeFormatter());
}
}
更新
不要在控制器中序列化对象.只需按原样返回对象即可.当您将json格式化程序附加到配置中时,Web api将为您完成此操作.
Don't serialize the object in the controller. Just return the object as is. Web api will do that for you as you have attached the json formatter to the configuration.
public class GuideController : ApiController
{
[AcceptVerbs("GET")]
[HttpGet]
public IHttpActionResult Get()
{
Item item = Item.GetTestData();
return Ok(item);
}
}
这篇关于C#API返回字符串,而不是XML包装的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!