简体   繁体   English

用于文件上传的OData v4自定义操作

[英]OData v4 Custom Action for File Upload

I have an OData controller with standard verbs for CRUD. 我有一个带有用于CRUD的标准动词的OData控制器。 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: 但是,当我尝试通过POST调用它时:

http://localhost/UploadFile 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 . 您需要将Action声明为EdmModel的一部分,在以下示例中,我假设您的Entity Type是Attachment ,并且您的控制器类名称是AttachmentsController By convention, your EntitySet name must then be Attachments 按照约定,您的EntitySet名称必须为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. 上面语句的重要部分是返回类型,如果您未在EdmModel中正确声明返回类型,则将发现端点返回406错误-即使您的方法执行正确,这也是无法接受的,这在第一次使您感到困惑你碰到它了。 This is because OData will still try to parse your response to match the Accept header from the request before completing the response. 这是因为OData在完成响应之前仍会尝试解析您的响应以匹配请求中的Accept标头。

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. 映射函数和操作时,请尝试使用“ nameof”,而不是“魔术字符串”或常量,以便编译器可以解决诸如错误定义路由之类的基本问题。

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. 使用这种方法,您不需要方法标题上的Route属性,并且该操作将包含在元数据文档中,因此会产生摇摇欲坠的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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