如何将该代码从MVC项目转换为web api? [英] How to convert that code please from MVC project to web api ?

查看:144
本文介绍了如何将该代码从MVC项目转换为web api?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题



如何将该代码从mvc项目转换为Web API





我在asp.net核心的mvc项目上工作2.1



我创建员工控制器,在里面我制作两个功能动作结果创建



新员工并保存如下:



我决定转换以上函数到web API,以便



如何根据上面的操作将创建新员工页面或表单获取和发布转换为Web API?



我尝试过:



problem

How to convert that code please from mvc project to web API


I work on mvc project in asp.net core 2.1

I create Employee Controller and inside it I make two function action result for create

new employee and save it as following :

I decided to convert above functions to web API so that

How to convert create new employee page or form get and post according to actions above to web API ?

What I have tried:

public IActionResult Create()
        {
           var model = new Employee();
            if (id == null)
            {
                
                model.EmployeeId = _repository.GetAll().Max(Employee => Employee.EmployeeId) + 1;
             }
            return View(model);
        }

      
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                _context.Add(employee);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(employee);
        }

推荐答案

通常,Web API构建将以很少的代码插入现有的模型和控制器变化。不同之处在于API没有前端。



您的表单将在独立的网页上或在其他项目中用户界面。从独立网页中,您可以使用AJAX提交表单。如果它是另一个服务器 - 客户端项目(MVC,Web窗体等),您也可以以编程方式将数据提交给API。



这里有一些关于如何使用的文档开始使用:

ASP.NET Web API 2入门(C#)| Microsoft Docs [ ^ ]
Generally the Web API build is going to be drop-in your existing Models and Controllers with very little code changes. What is going to be different is that APIs do not have a front end.

Your forms are going to be on stand alone web pages or within another project that does have a user interface. From stand-alone web pages you would use AJAX for submission of the form. If it is another server-client project (MVC, Web Forms, etc) you could also programmatically submit the data to the API.

Here is some documentation on how to get started:
Get Started with ASP.NET Web API 2 (C#) | Microsoft Docs[^]


正如解决方案1中已经提到的,MadMyche,你不能简单地转换你的应用程序到API,其中API本身是应用程序开发的单独方式或方法。 API有很多要求,例如无状态,无头,跨平台和跨设备。 API直接在HTTP协议上工作,不需要浏览器来显示内容。以这种方式,将不需要视图等。



具象状态转移 - 维基百科 [ ^ ]



这个方式,您将使用数据交换格式,如JSON或XML,然后使用这些格式返回数据,然后从客户端访问它。所以这就是问题,您需要将视图更改为模型 - 返回数据而不是HTML文档。然后可以在任何地方访问该数据并进行解析。



请参阅我的这篇文章,了解这是如何发生的, ASP.NET 5 Web API RESTful CRUD和Windows 10本机应用程序 [ ^ ]



您的代码将更改为以下代码,

As already mentioned in Solution 1, by MadMyche, you cannot simply convert your applications to an API, where API itself is a separate way or method of development of applications. An API has so many requirements, such as being stateless, headless, and cross-platform, and cross-device. APIs work directly on the HTTP protocol, and do not require a browser to display the content. In this fashion, the Views etc won't be needed.

Representational state transfer - Wikipedia[^]

This way, you would be using a data-interchange format, like JSON or XML, and then return the data using these formats, and then access that from the client. So here is the thing, you need to change the View to the Models—you return the data instead of an HTML document. Then that data can be accessed anywhere, and parsed.

Please see this article of mine to understand how this can happen, ASP.NET 5 Web API RESTful CRUDs and Windows 10 native application[^]

Your code, would be changed to the following code,
// Change from IActionResult to the data, this will be serialized to JSON (or XML)
[HttpPost]
public Employee Create()
{
    var model = new Employee();
    if (id == null)
    {
        
        model.EmployeeId = _repository.GetAll().Max(Employee => Employee.EmployeeId) + 1;
    }

    // Return the data itself, not the View
    return model;
}

// You can do the same "async" thing using API too, just return the data
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<Employee> Create(Employee employee)
{
    // See below for more ways to capture, bind and validate the model values.
    _context.Add(employee);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));

    // Return the data again
    return employee;
}

这是另一个有趣的事情,因为您使用的是API,您的用户可以使用任何方法上传数据,查询字符串,通过HTTP正文发布,发送文件,发送为形式数据,无论如何。您需要通过这些方法检查数据,例如 [FromBody] 等。



ASP.NET Core中的模型绑定Microsoft Docs [ ^ ]

Here is another interesting thing, since you are using an API, your users can upload the data using any method, query string, POST it via HTTP body, send a file, send as form-data, whatever. You need to check the data via those methods, such as [FromBody], etc.

Model Binding in ASP.NET Core | Microsoft Docs[^]


这篇关于如何将该代码从MVC项目转换为web api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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