Media Resource Support for OData POST in Web API

ぐ巨炮叔叔 提交于 2019-12-21 07:27:29

问题


I would like to create oData controller to upload files

FileDto

  1. FileId
  2. NameWithExtension (Type: String)
  3. Metadata (Type: List)
  4. Content (Type: Stream)

=========================Http Request Actions==================

• GET: ~/Files({id})

Content-Type: application/json
Result: FileDto without Content

• GET: ~/Files({id})

Content-Type: application/octet-stream
Result: Stream of the File only

• POST: ~/Files

Content-Type: ?
Body: FileDto with Content
Result: FileId

Not sure how i can achieve this when coupled with OData.

Thanks in advance


回答1:


This page explains how to create an oDataController.

1) To install the package on your project, open the console manager and type this:

Install-Package Microsoft.AspNet.Odata

2) Open your WebApiConfig.cs and, inside Register method, add this code:

 ODataModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<FileDto>("File");            
            config.MapODataServiceRoute(
                routeName: "ODataRoute",
                routePrefix: null,
                model: builder.GetEdmModel());

3) Create your oDataController replacing the yourDataSourceHere to use your own class:

public class FileController : ODataController
{
    [EnableQuery]
    public IQueryable<FileDto> Get()
    {
        return yourDataSourceHere.Get();
    }

    [EnableQuery]
    public SingleResult<FileDto> Get([FromODataUri] int key)
    {
        IQueryable<FileDto> result = yourDataSourceHere.Get().Where(p => p.Id == key);
        return SingleResult.Create(result);
    }

    public IHttpActionResult Post(FileDto File)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        yourDataSourceHere.Add(product);

        return Created(File);
    }
}

OBS: To test this solution, I changed the FileDto's property Content. More specifically, it's type! From Stream to byte[]. Posted the content as Base64 string.



来源:https://stackoverflow.com/questions/23440933/media-resource-support-for-odata-post-in-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!