【问题标题】:Validate a Action with ASP.NET Web API使用 ASP.NET Web API 验证操作
【发布时间】:2014-01-10 10:06:18
【问题描述】:

在我的解决方案中,我有三个项目:

App.Model

在这个项目中,我有我的模型类和单个 dbcontext(代码优先)

    public class Customer
{
    [Key]
    public int ID { get; set; }

    public string  Name { get; set; }
}

App.UI - MVC 项目

这里有控制器(Get 方法)和视图

    public ActionResult Create()
    {
        return View();
    }

App.Validation - ASP.NET Web API 项目

这里只有控制器用于验证(Post 方法)。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="ID,Name")] Customer customer)
    {
        if (ModelState.IsValid)
        {
            db.Customer.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(customer);
    }

当我从 UI 项目中的控制器调用 post 操作时,我将 API 项目中的控制器执行 UI 控制器的验证。

我必须更改 RouteConfig 和 WebApiConfig 中的路由规则,或者我需要将操作作为参数传递给 API?

【问题讨论】:

  • 您是否有尝试传递给 asp.net web api 应用程序的模型样本?
  • 我修改了我的问题

标签: asp.net-mvc asp.net-web-api


【解决方案1】:

一种方法是从 UI 控制器操作调用 API 控制器操作。

    [HttpPost]
    public ActionResult Create(Customer customer)
    {
        try
        {
            var json = JsonConvert.SerializeObject(customer);
            Encoding encoding = Encoding.UTF8;

            var requestBody = encoding.GetBytes(json)
            var uri = ""; // replace empty string with the uri of the web Api project

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Timeout = 999;
            request.ContentType = "application/json";
            request.Method = "put";
            request.ContentLength = requestBody.Length;
            request.GetRequestStream().Write(requestBody, 0, requestBody.Length);
            request.GetResponse();

            return RedirectToAction("Index");
        }
        catch (WebException e)
        {
            // handle exception
            return View(customer);
        }
    }

Web API 操作可以是这样的:

[HttpPost]
public HttpResponseMessage Create(Customer customer)
{
    if (ModelState.IsValid)
    {
        db.Customer.Add(customer);
        db.SaveChanges();
        return Request.CreateResponse(HttpStatusCode.OK);
    }        
    else
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest);
    }
}

【讨论】:

猜你喜欢
  • 2015-08-24
  • 1970-01-01
  • 2017-04-13
  • 2023-04-08
  • 2012-06-16
  • 2021-05-18
  • 2015-09-17
  • 2018-11-23
  • 1970-01-01
相关资源
最近更新 更多