我想创建一个图像处理程序,但我在使用Web API 2或正常的通用处理程序(ashx)之间撕裂,
@H_404_6@解决方法
过去我已经实施了两个,但哪一个是最正确的.
我发现一个旧的SO帖子LINK,但它仍然真的相关吗?
WebApi是完全有能力的,我更喜欢它.另一个答案是JSON和XML是默认的,但您可以添加自己的MediaFormatter并为任何模型提供任何内容类型.这允许您执行内容协商,并根据Accept标头或文件扩展名提供不同的内容.假装我们的模型是“用户”.想象一下,要求“用户”为json,xml,jpg,pdf.使用WebApi,我们可以使用文件扩展名或Accept标头,要求/ Users / 1或用户/ 1.json为JSON,用户/ 1.jpg为jpg,Users / 1.xml为xml,/Users/1.pdf对于pdf等等,所有这些也可能只是/ Users / 1与不同的接受标题与质量,所以您的客户可以要求用户/ 1与接受头首先要求jpg,但回到png.
这是一个如何为.jpg创建格式化程序的例子.
public class JpegFormatter : MediaTypeFormatter { public JpegFormatter() { //this allows a route with extensions like /Users/1.jpg this.AddUriPathExtensionMapping(".jpg","image/jpeg"); //this allows a normal route like /Users/1 and an Accept header of image/jpeg this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpeg")); } public override bool CanReadType(Type type) { //Can this formatter read binary jpg data? //answer true or false here return false; } public override bool CanWriteType(Type type) { //Can this formatter write jpg binary if for the given type? //Check the type and answer. You could use the same formatter for many different types. return type == typeof(User); } public override async Task WriteToStreamAsync(Type type,object value,Stream writeStream,HttpContent content,TransportContext transportContext) { //value will be whatever model was returned from your controller //you may need to check data here to know what jpg to get var user = value as User; if (null == user) { throw new NotFoundException(); } var stream = SomeMethodToGetYourStream(user); await stream.CopyToAsync(writeStream); } }
现在我们需要注册我们的格式化程序(通常是App_Start / WebApiConfig.cs)
public static class WebApiConfig { public static void Register(HttpConfiguration config) { ... //typical route configs to allow file extensions config.Routes.MapHttpRoute("ext","{controller}/{id}.{ext}"); config.Routes.MapHttpRoute("default","{controller}/{id}",new { id = RouteParameter.Optional }); //remove any default formatters such as xml config.Formatters.Clear(); //order of formatters matter! //let's put JSON in as the default first config.Formatters.Add(new JsonMediaTypeFormatter()); //now we add our custom formatter config.Formatters.Add(new JpegFormatter()); } }
最后,我们的控制器
public class UsersController : ApiController { public IHttpActionResult Get(int id) { var user = SomeMethodToGetUsersById(id); return this.Ok(user); } }
您的控制器将不必更改,因为您添加不同的格式化程序.它只是返回你的模型,然后格式化程序在后面的踢.我喜欢格式化,因为它提供了这么丰富的api.您可以在WebApi website上阅读有关格式化程序的更多信息.