如何限制Web API中的POST [英] How to limit POST in web API

查看:60
本文介绍了如何限制Web API中的POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的SiteController.cs文件中有以下 POST 代码.

I have the following POST code in my SiteController.cs file.

// POST: api/site
[ResponseType(typeof(site))]
public IHttpActionResult Postsite(site site)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.site.Add(site);
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = site.id }, site);
}

我有一个Web表单,我在其中使用代码对数据库中Site表中的字段进行 POST .

I have a web form where I'm using code to POST the fields to the Site table in my database.

在数据库中(以及在我的site.cs类中),站点具有5个属性:ID,名称,城市,州和国家/地区.当我使用 POST 表单时,它将添加到该表中.

In the database (and also in my site.cs class), Site has 5 attributes: ID, Name, City, State, and Country. When I use the POST form it adds to this table.

我想做的是检查上面的 POST 代码,如果表/API结果中该类的 Name 属性已经存在该名称.我将如何使这种 POST 方法能够进行此检查?

What I want to do is check in the POST code above if the Name attribute of the class already exists with that name in the table/API results. How would I go about making this POST method capable of making this check?

我尝试做类似 if site.name ==(???)的操作,然后抛出一个错误,但是我不确定(???)中会发生什么检查其余的API结果.

I've tried doing something like if site.name == (???) and then throw an error, but I'm not sure what would go in the (???) to check the rest of the API's results.

推荐答案

检查记录是否首先存在

if(!db.site.Any(s => s.Name == site.name))
{
    db.site.Add(site);
    db.SaveChanges();
}

如果您想获取状态,请查看以下示例代码:

If you like to get the status, here is some sample code:

// POST: api/site
public HttpResponseMessage Postsite(site site)
{
       if(!db.site.Any(s => s.Name == site.name))
       {
           db.site.Add(site);
           db.SaveChanges();
           var message = Request.CreateResponse(HttpStatusCode.Created, site);
           message.Headers.Location = new Uri(Request.RequestUri + site.Id.ToString());
           return message;
       }
       else
       {
          return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
       }

}

这篇关于如何限制Web API中的POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆