简体   繁体   中英

OData v4 Custom Action for File Upload

I have an OData controller with standard verbs for CRUD. Everything is working fine. Now I need to add a custom action to perform file upload. I try to add a method to my existing controller like this:

[HttpPost]
[Route("UploadFile")]
public async Task<HttpResponseMessage> UploadFile()
{
    //handle uploaded content logic here...
}

But when I try to invoke it by doing a POST:

http://localhost/UploadFile

I get this error:

System.InvalidOperationException: No non-OData HTTP route registered.

What should I do for this custom action to allow file upload?

You need to declare the Action as part of the EdmModel, in the following example I am assuming that your Entity Type is Attachment , and your controller class name is AttachmentsController . By convention, your EntitySet name must then be Attachments

var attachments = builder.EntitySet<Attachment>("Attachments");
attachments.Action(nameof(AttachmentsController.UploadFile))
    .Returns<System.Net.Http.HttpResponseMessage>();

The important part of the above statement is the return type, if you do not declare the return type correctly in your EdmModel then you will find your endpoints returning 406 errors - Unacceptable, even though your method executes correctly, which is really confusing the first time you run into it. This is because OData will still try to parse your response to match the Accept header from the request before completing the response.

Try to use 'nameof' when mapping functions and actions instead of 'magic strings' or constants so that the compiler can pickup basic issues like wrongly defined route.

With this approach you do not need the Route attribute on the method header and the action will be included in the metadata document and therefore swagger outputs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM