webapi返回json字符串

第一种

直接在方法中返回json。

public class DefaultController : ApiController
{
    [HttpGet]
    public IHttpActionResult Now()
    {
        return Json(new { n = new Random().Next(10, 100), t = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });
    }
}

不过一些内部返回的默认是xml格式,比如访问一个不存在的地址/api/xxx

<Error>
<Message>
找不到与请求 URI“http://localhost:5566/api/xxx”匹配的 HTTP 资源。
</Message>
<MessageDetail>未找到与名为“xxx”的控制器匹配的类型。</MessageDetail>
</Error>

第二种

移除xml格式的支持(因为默认xml比json的优先,移除xml后默认就是json了)

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API 配置和服务

        //移除xml格式的支持
        config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

        // Web API 路由
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

第三种

自定义内容响应格式IContentNegotiator,需要引用System.Net.Http.Formatting程序集。

public class SimpleContentNegotiator : IContentNegotiator
{
    private readonly MediaTypeFormatter _formatter;
    private readonly string _mediaType;

    public SimpleContentNegotiator(MediaTypeFormatter formatter, string mediaType)
    {
        _formatter = formatter;
        _mediaType = mediaType;
    }

    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
    {
        var result = new ContentNegotiationResult(_formatter, new MediaTypeHeaderValue(_mediaType));
        return result;
    }
}
// Web API 配置和服务

//自定义内容响应格式
config.Services.Replace(typeof(IContentNegotiator), new SimpleContentNegotiator(new JsonMediaTypeFormatter(), "application/json"));

猜你喜欢

转载自www.cnblogs.com/junio/p/10765602.html