I would like to create oData controller to upload files
FileDto
=========================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
In Solution Explorer, right click on Models folder > Add > Class > Name your class. Now, we are going to create a Controller. Right click on the Controllers folder > Add > Controller> selecting Web API 2 OData v3 Controller with actions, using Entity Framework > click Add.
The Open Data Protocol (OData) is a data access protocol for the web. OData provides a uniform way to query and manipulate data sets through CRUD operations (create, read, update, and delete). ASP.NET Web API supports both v3 and v4 of the protocol.
A request that might take a long time to process should be performed without blocking the client that submitted the request. The web API can perform some initial checking to validate the request, initiate a separate task to perform the work, and then return a response message with HTTP code 202 (Accepted).
OData defines parameters that can be used to modify an OData query. The client sends these parameters in the query string of the request URI. For example, to sort the results, a client uses the $orderby parameter: http://localhost/Products?$orderby=Name. The OData specification calls these parameters query options.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With