미디어 유형을 사용하면 API가 페이로드의 데이터를 해석하는 방법을 클라이언트에 알릴 수 있습니다. HTTP 프로토콜에서 미디어 유형은 가장 일반적인 웹 형식인 HTML, JSON 및 XML에 각각 해당하는 text/html, application/json 및 application/xml과 같은 식별자로 지정됩니다. application/vnd.api+json과 같은 다른 APIspecificMedia 유형도 있습니다.
다음은 미디어 유형으로 보내야 하는 버전입니다.
application/vnd.demo.students.v1+json StudentsV1Controller application/vnd.demo.students.v2+json StudentsV2Controller

자체 CustomControllerSelector 추가 위의 오류를 수정합니다.
CustomControllerSelector -
예시
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
namespace WebAPI.Custom{
public class CustomControllerSelector : DefaultHttpControllerSelector{
private HttpConfiguration _config;
public CustomControllerSelector(HttpConfiguration config) : base(config){
_config = config;
}
public override HttpControllerDescriptor SelectController(HttpRequestMessage
request){
var controllers = GetControllerMapping();
var routeData = request.GetRouteData();
var controllerName = routeData.Values["controller"].ToString();
string versionNumber = "";
string regex = @"application\/vnd\.demo\.([a-z]+)\.v(?<version>[0-9]+)\+([a-z]+)";
var acceptHeader = request.Headers.Accept
.Where(a => Regex.IsMatch(a.MediaType, regex,
RegexOptions.IgnoreCase));
if (acceptHeader.Any()){
var match = Regex.Match(acceptHeader.First().MediaType,
regex, RegexOptions.IgnoreCase);
versionNumber = match.Groups["version"].Value;
}
HttpControllerDescriptor controllerDescriptor;
if (versionNumber == "1"){
controllerName = string.Concat(controllerName, "V1");
}
else if (versionNumber == "2"){
controllerName = string.Concat(controllerName, "V2");
}
if (controllers.TryGetValue(controllerName, out controllerDescriptor)){
return controllerDescriptor;
}
return null;
}
}
} WebApi.Config.cs -
예시
public static class WebApiConfig{
public static void Register(HttpConfiguration config){
config.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector(config));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
} StudentV1Controller -
예시
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class StudentV1Controller : ApiController{
List<StudentV1> students = new List<StudentV1>{
new StudentV1{
Id = 1,
Name = "Mark"
},
new StudentV1{
Id = 2,
Name = "John"
}
};
public IEnumerable<StudentV1> Get(){
return students;
}
public StudentV1 Get(int id){
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
} StudentV2Controller -
예시
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class StudentV2Controller : ApiController{
List<StudentV2> students = new List<StudentV2>{
new StudentV2{
Id = 1,
FirstName = "Roger",
LastName = "Federer"
},
new StudentV2{
Id = 2,
FirstName = "Tom",
LastName = "Bruce"
}
};
public IEnumerable<StudentV2> Get(){
return students;
}
public StudentV2 Get(int id){
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
} 아래 출력은 사용자 지정 미디어 유형의 버전 관리를 통해 StudentV1 및 StudentV2 컨트롤러에서 얻은 결과를 보여줍니다.


이제 사용자 정의 미디어 유형을 사용하여 xml 형식으로 동일한 출력을 얻으려면 webapiconfig.cs
에 아래 사용자 정의 미디어 유형을 추가하십시오.예시
public static void Register(HttpConfiguration config){
config.MapHttpAttributeRoutes();
config.Services.Replace(typeof(IHttpControllerSelector), new
CustomControllerSelector(config));
config.Formatters.XmlFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("application/vnd.demo.student.v1+xml"));
config.Formatters.XmlFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("application/vnd.demo.student.v2+xml"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}

위의 예에서 출력이 사용자 정의 미디어 유형에 지정된 XML 형식임을 알 수 있습니다.