MVCÎÒÏàП÷λ¿Ï¶¨¶¼ÓÐËùÁ˽âÁË£¬½ñÌìÎÒÃÇÒ»ÆðÀ´¿´¿´ASP.NET MVC 4 Web API ѧϰ ÕýÈ··µ»ØJSONÊý¾Ý·½·¨£¬Ï£ÍûÎÄÕ¶Ը÷λÓаïÖú£®
web api ±¾À´¾Í¿ÉÒÔ·µ»Øjson¸ñʽµÄ,ΪʲôÎÒÃÇÒª»¹¶ÔËü×öһЩÐÞ¸ÄÄØ£¿
ÒòΪweb apiĬÈÏ·µ»ØµÄÊÇxml,ÔÚÌá½»ÇëÇóµÄÊÇÉèÖÃÁË Content-Type: application/json;
·µ»ØµÄ²ÅÊÇJSON¸ñʽµÄÊý¾Ý!
µ«ÊÇÔõô×öµ½ÈÃËüÖ»ÊÇ·µ»ØJSON¸ñʽµÄÊý¾ÝÄØ£¿
ÓÐʱºò¾Í»áÓöµ½ÕâÖÖÐèÇó£¡
ÕâÊÇÎÒ×ʼµÄ×ö·¨]
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
¿ÉÒÔ·µ»ØJSON¸ñʽÁË,µ«ÊÇĪÃûÆäÃîµÄ¶à³öÁ˸ö$id ²»¶®ÄÄÀïÀ´µÄ£¡
×îºóÕýÈ·µÄ°ì·¨ÊÇʹÓÃ×Ô¶¨ÒåµÄÖ»·µ»ØJson ResultµÄcontent negotiation´úÌæWeb ApiÖÐĬÈϵÄcontent negotiation¡£ Connegͨ¹ýʵÏÖIContentNegotiatorµÄNegotiator·½·¨ÊµÏÖÀ©Õ¹¡£Negotiator·½·¨·µ»ØContentNegotiationResult£¨Ëü°ü×°ÁËÄãÑ¡ÔñµÄheadersºÍformatter£©¡£ÏÂÃæµÄ·½·¨Í¨¹ý´«µÝÒ»¸öJsonMediaTypeFormatter¸ø×Ô¶¨ÒåµÄconneg negotiator£¬ÈÃËüÒ»Ö±·µ»Øapplicaton/json µÄcontent-typeÒÔ¼°JsonMediaTypeFormatter¡£ÕâÖÖ·½·¨±ÜÃâÁËÿ´ÎÇëÇó¶¼ÒªÖØд´½¨Ò»´Îformatter¡£
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}
½ÓÏÂÀ´£¬ÄãÐèÒªÔÚHttpConfigurationʵÀýÉÏ×¢²áÄãµÄеÄʵÏÖ»úÖÆ£º
var jsonFormatter = new JsonMediaTypeFormatter();
//optional: set serializer settings here
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
ͨ¹ýÌ滻ĬÈϵÄDefaultContentNegotiator£¬ÎÒÃÇʹÓÃÎÒÃÇ×Ô¶¨ÒåµÄJsonContentNegotiator£¬ËüÖ»Ö§³ÖJson£¬¶øÇÒ¿ÉÒÔÂíÉÏ·µ»Ø¡£
Èç¹ûÄãÏë¸üÉîÈëµÄÁ˽âContent NegotiationµÄ֪ʶ£¬Äã¿ÉÒԲ鿴×÷ÕßµÄÕâƪÎÄÕ¡£
×ܽá
ͨ¹ýʹÓÃ×Ô¶¨ÒåµÄJsonContentNegotiatorÌ滻ϵͳĬÈϵÄDefaultContentNegotiator£¬ºÜºÃµÄʵÏÖWeb ApiÖ»·µ»ØJsonµÄ¹¦ÄÜ£¬¶øÇÒûÓжîÍâµÄ¿ªÏú¡£
¡¡