加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 在EntitySetController中创建自定义操作

发布时间:2020-12-16 06:32:48 所属栏目:asp.Net 来源:网络整理
导读:我在.Net 4.5中有一个oData应用程序. oData端点工作正常,但我想在控制器上创建自定义操作,以便在给定电子邮件地址时在Customer记录上设置标志. 这是我的客户端代码(使用AngularJS): $http({ method: 'POST',url: '/odata/Customers/SetAlertFlag',data: { '
我在.Net 4.5中有一个oData应用程序. oData端点工作正常,但我想在控制器上创建自定义操作,以便在给定电子邮件地址时在Customer记录上设置标志.

这是我的客户端代码(使用AngularJS):

$http({
        method: 'POST',url: '/odata/Customers/SetAlertFlag',data: { 'email': 'test@test.com'}
    }).success(function (data,status,headers,config) {
        // ...
    }).error(function (data,config) {
        // ...
    });

这是我的服务器代码:

public class CustomersController : EntitySetController<Customer,int>
{
    private DBEntities db = new DBEntities();

    // ... other generated methods here


    // my custom method
    [HttpPut]
    public Boolean SetAlertFlag([FromBody] string email)
    {
        return true;
    }
}

永远不会调用服务器方法.当我在浏览器http:// localhost:60903 / odata / Customers / SetAlertFlag中输入此URL时出现此错误:“检测到无效操作.”SetAlertFlag’不是可以绑定到’Collection([Skirts.Models.客户Nullable = False])’.“

EntitySetController类可以没有自定义方法吗?我该怎么做呢?

解决方法

OData中的操作使用特定格式,需要POST.你需要:

将操作添加到EDM:

ActionConfiguration action = modelBuilder.Entity<Customer>().Collection.Action("SetAlertFlag");
action.Parameter<string>("email");

声明这样的动作:

[HttpPost]
public int SetAlertFlag(ODataActionParameters parameters) 
{ 
    if (!ModelState.IsValid)
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

    string email = (string)parameters["email"];
}

调用这样的动作:

POST http://localhost/odata/Customers/SetAlertFlag
Content-Type: application/json

{"email":"foo"}

在这里阅读更多:http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-actions

(我只是键入了这些代码片段,因此可能会出现一些错误,但这就是想法.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读