.NET Core Web API:您需要了解的最少知识(第1部分,共2部分)

背景 (Background)

Recently, while easing into using a .NET Core Web API, I discovered that I wasn't sure of the correct way to post data to a Web API via the XMLHttpRequest (XHR) object.

最近,在放松使用.NET Core Web API的同时,我发现我不确定通过XMLHttpRequest (XHR)对象将数据发布到Web API的正确方法。

I wasn't sure about:

我不确定:

  1. how to add the data to the XHR object so that it would show up in the post body.

    如何将数据添加到XHR对象以使其显示在帖子正文中。
  2. how to ensure the Web API would automatically transform the posted JSON into my target domain object.

    如何确保Web API将发布的JSON自动转换为我的目标域对象。

I was getting all kinds of errors and I couldn't tell if I had the client side wrong or the Web API side wrong, or both. I discovered that both were wrong, but I also discovered that it is quite difficult to find a definitive answer to this even though you'd think it was a common pairing (plain JavaScript XHR posting to Web API).

我遇到了各种各样的错误,我无法分辨是客户端错误还是Web API错误,或者两者都不是。 我发现两者都是错误的,但是即使您认为这是常见的配对(将纯JavaScript XHR发布到Web API),也很难找到一个明确的答案。

本文涵盖的内容 (What this Article Covers)

  1. Creating a .NET Core Web API project (via command-line) - I use Visual Studio Code running on Ubuntu Linux

    创建一个.NET Core Web API项目(通过命令行)-我使用在Ubuntu Linux上运行的Visual Studio Code
  2. Adding a Web API method which can be posted to

    添加可以发布到的Web API方法
  3. Altering the Web API application so it will serve an index.htm file (for testing our Web API)

    更改Web API应用程序,使其将提供index.htm文件(用于测试我们的Web API)

  4. Setting up a simple index.htm and main.js file that we use to post to the Web API

    设置一个简单的index.htmmain.js文件,我们用它来发布到Web API

  5. Configuring an XMLHttpRequest (XHR) to post JSON to the Web API

    配置XMLHttpRequest (XHR)以将JSON发布到Web API

介绍 (Introduction)

I'm assuming you already have the latest copy of Visual Studio or Visual Studio Code on your machine.

我假设您已经在计算机上安装了Visual Studio或Visual Studio Code的最新副本。

Of course, you'll also need to ensure you have the latest version of .NET Core installed too. If you need that, you can go to https://dotnet.microsoft.com/download^.

当然,您还需要确保也安装了最新版本的.NET Core。 如果需要,可以访问https://dotnet.microsoft.com/download^

I'm running Visual Studio Code on Ubuntu Linux so I do everything from the command-line but if you're running on Windows and using Visual Studio, you can create the .NET Core Web API using a wizard. The command-line really isn't difficult with .NET Core though and you'll probably find it quite satisfying.

我在Ubuntu Linux上运行Visual Studio Code,因此我可以从命令行执行所有操作,但是如果您在Windows上运行并使用Visual Studio,则可以使用向导创建.NET Core Web API。 .NET Core的命令行实际上并不难,您可能会发现它非常令人满意。

创建新项目 (Create the New Project)

To get started, take the following steps:

首先,请执行以下步骤:

  1. Open a Console (or terminal).

    打开一个控制台(或终端)。
  2. Navigate to a directory where you want to create a new project.

    导航到要创建新项目的目录。
  3. Type the following command: dotnet new webapi --name MainWebAPI

    键入以下命令: dotnet new webapi --name MainWebAPI

将创建一个新文件夹 (A New Folder Will Be Created)

When you type that command and hit <ENTER>, it will create a new subfolder named MainWebAPI and add all of the project files into the directory.

当您键入该命令并按<ENTER>时 ,它将创建一个名为MainWebAPI的新子文件夹,并将所有项目文件添加到该目录中。

If it was successful, you will see something like the following:

如果成功,您将看到类似以下内容:

create .net web api project

If you get some kind of error that the command is not recognized, then you probably do not have the .NET Core SDK installed. To determine the version of the .NET you have installed, you can try the following command:

如果您收到某种无法识别该命令的错误,则可能您没有安装.NET Core SDK。 要确定已安装的.NET版本,可以尝试以下命令:

dotnet --version

Mine replies with 3.1.202.

我的回答是3.1.202。

If all of that went well, then you have a very basic Web API that runs on top of .NET Core.

如果一切顺利,那么您就可以在.NET Core上运行一个非常基本的Web API。

运行Web API项目 (Run the Web API Project)

Let's make sure that the project will compile and run. It's very easy.

让我们确保项目可以编译并运行。 很简单

First of all, just change directory into the newly created project directory: cd MainWebAPI

首先,只需将目录更改为新创建的项目目录: cd MainWebAPI

Next, type: dotnet run

接下来,键入: dotnet run

.NET will build and start the Web API.

.NET将构建并启动Web API。

It'll look something like the following:

它看起来像以下内容:

get dotnet version

只是建立项目 (Just Build the Project)

By the way, if you had just wanted to build the project, you could've typed: dotnet build

顺便说一句,如果您只是想构建项目,则可以输入: dotnet build

实际使用中的Web API (See the Web API in Action)

To see the Web API do something, you can hold your CTRL button and click the link (https://localhost:5001) that is displayed in the console window. When you do, your default browser will open the link.

要查看Web API的功能,可以按住CTRL键并单击控制台窗口中显示的链接(https:// localhost:5001)。 完成后,默认浏览器将打开该链接。

But it's not very amazing because you haven't made a call to any Web API method.

但这并不十分令人惊奇,因为您尚未调用任何Web API方法。

You'll just see a blank web page.

您只会看到一个空白网页。

通过Get的一种Web API方法 (One Web API Method Via Get)

However, there is one method that you can call via the GET. Try this URL: https://localhost:5001/WeatherForecast/^.

但是,您可以通过GET调用一种方法。 尝试以下URL: https:// localhost:5001 / WeatherForecast / ^

That calls the default Get method on the WeatherForecastController* class. That method just generates some random WeatherForecast* domain objects and then sends them to the client as JSON.

这将在WeatherForecastController *类上调用默认的Get方法。 该方法只是生成一些随机的WeatherForecast *域对象,然后将它们作为JSON发送给客户端。

* I'll show you both of these classes in just a moment when we look at the code.

*当我们看一下代码时,我将向您展示这两个类。

You'll see something like one of the following two images in your browser (depending upon how your browser renders the JSON).

您将在浏览器中看到类似以下两个图像之一的图像(取决于浏览器呈现JSON的方式)。

web api json formatted

web api raw JSON

Now that you've seen the code run, let's take a look at the code and begin altering the WeatherForecastController so that we can post JSON to it and have it turn our JSON into a domain object automatically.

既然您已经看到了代码的运行,让我们看一下代码,然后开始更改WeatherForecastController以便我们可以向其发布JSON,并使它自动将JSON转换为域对象。

Visual Studio程式码 (Visual Studio Code)

I'm going to be using Visual Studio Code (VSC) throughout this article, but you can still use Visual Studio if you prefer.

在本文中,我将始终使用Visual Studio Code(VSC),但如果愿意,您仍然可以使用Visual Studio。

Go ahead and start Visual Studio Code (VSC) and then we'll open the project.

继续并启动Visual Studio Code(VSC),然后打开项目。

开启资料夹 (Open a Folder)

To load the project in VSC, you:

要在VSC中加载项目,请执行以下操作:

  1. go to the main menu

    进入主菜单
  2. choose the [File...]menu item

    选择[文件...]菜单项
  3. choose the [Open Folder...]

    选择[打开文件夹...]
  4. Navigate to the folder that was created when we created the project and select it

    导航到创建项目时创建的文件夹,然后选择它

When you follow those steps, you'll see something like the following:

当您按照这些步骤,您将看到类似以下内容:

visual studio code

重点地区 (Highlighted Areas)

I've highlighted a few areas in VSC so we can talk about them.

我在VSC中强调了一些领域,因此我们可以讨论它们。

工具列 (Toolbar)

The first section is the toolbar which includes a few icons.

第一部分是工具栏,其中包含一些图标。

档案检视 (File View)

The currently selected one is highlighted in white and indicates that File View is displayed. You can see that in the second section there is a list of files. However, if you choose one of the other icons, this section will change.

当前选定的图标以白色突出显示,并显示文件视图。 您可以在第二部分中看到文件列表。 但是,如果您选择其他图标之一,则此部分将更改。

调试视图 (Debug View)

During this article,we will also use the Debug item to show you how you can step through your Web API code using VSC. The Debug item is indicated by the

debug icon.

在本文中,我们还将使用“调试”项向您展示如何使用VSC逐步遍历Web API代码。 调试项由

However, to use the debugger in VSC you have to make sure that you have the C# Extensions plugin installed and running.

但是,要在VSC中使用调试器,必须确保已安装并正在运行C#Extensions插件。

插件视图 (Plugins View)

The plugins view is indicated by the

plugins icon.

插件视图由

You can see that section 4 of the VSC overview image that I provided above is actually VSC warning me that the C# Extension plugin needs to be added to the project so we can debug the code. If you see that and click the [Yes] button, then it will add it to the project. However, you may not see that if the extension hasn't been added to your system.

您可以看到我上面提供的VSC概述图像的第4部分实际上是VSC,警告我需要将C#Extension插件添加到项目中,以便我们可以调试代码。 如果看到该内容,然后单击[是]按钮,它将把它添加到项目中。 但是,如果未将扩展名添加到系统中,则可能看不到。

Also, that pop-up tends to disappear quickly. That's okay though, because you can click the Plugins icon and add the plugin to your system and project any time.

同样,该弹出窗口往往会Swift消失。 没关系,因为您可以单击“插件”图标,然后随时将插件添加到系统和项目中。

Here's what it looks like once it is installed and activated:

安装和激活后的外观如下:

plugin view with C# extensions
主编区 (Main Editor Area)

Finally, you can see that the main editor area (area 3 on the VSC image above) is currently displaying notes about the current version of VSC. This is the area where each file will display when you choose them from the File Viewer area.

最后,您可以看到主编辑器区域(上方VSC图像上的区域3)当前正在显示有关VSC当前版本的注释。 从“文件查看器”区域中选择每个文件时,这是将显示每个文件的区域。

Now that you are more familiarized with VSC, let's start looking at the WeatherForecastController.

现在您对VSC更加熟悉了,让我们开始看看WeatherForecastController

检查WeatherForecastController (Examining the WeatherForecastController)

在子目录中打开文件 (Opening a File in a SubDirectory)

Make sure you are on File View. Next, in the File View, find the Controllers directory. It will have a down right-arrow (great-than sign) pointing at the Controllers name. That's indicating a folder that is currently collapsed. Click on the Controllers folder and select the WeatherForecaseController.cs that appears, and it will display in the editor area.

确保您在“文件视图”上。 接下来,在文件视图中,找到Controllers目录。 它将有一个向下的右箭头(大于号)指向Controllers名称。 这表示当前已折叠的文件夹。 单击Controllers文件夹,然后选择出现的WeatherForecaseController.cs ,它将显示在编辑器区域中。

控制器:应用逻辑层 (Controller: Application Logic Layer)

I'm not going to explain every aspect of the Controller code. You can think of the controller in general as the application logic layer. Here's the basics of what happens.

我不会解释Controller代码的每个方面。 您通常可以将控制器视为应用程序逻辑层。 这是发生的事情的基础。

A user requests an action (function or method) on a Controller by sending an HTTP Command (GET, POST, PUT, etc.^) to the named Controller (described by the URL) on the server. Note: In this article, we will only deal with the POST command.

用户通过向服务器上的命名控制器(由URL描述)发送HTTP命令( GET,POST,PUT等^ )来请求Controller上的操作(功能或方法)。 注意 :在本文中,我们将仅处理POST命令。

As developers, we can write code in the Controller method that runs application logic that provides specific functionality. It's really that simple.

作为开发人员,我们可以在Controller方法中编写代码,该方法运行提供特定功能的应用程序逻辑。 真的就是这么简单。

The Get method that the project template included in the Controller looks like:

Controller包含的项目模板的Get方法如下所示:

[HttpGet]
 public IEnumerable<WeatherForecast> Get()
 {
     Console.WriteLine("in get...");
     var rng = new Random();
     return Enumerable.Range(1, 5).Select(index => new WeatherForecast
     {
         Date = DateTime.Now.AddDays(index),
         TemperatureC = rng.Next(-20, 55),
         Summary = Summaries[rng.Next(Summaries.Length)]
     })
     .ToArray();
 }


It's probably obvious, but the [HttpGet] method decorator tells the compiler to make this method available via HTTP Get.

这可能很明显,但是[HttpGet]方法装饰器告诉编译器通过HTTP Get使此方法可用。

This method simply generates an array of five WeatherForecast objects (domain objects) and returns them. They will be serialized to JSON automatically and that is what we saw in the browser earlier.

该方法仅生成五个WeatherForecast对象(域对象)的数组并返回它们。 它们将被自动序列化为JSON,这就是我们之前在浏览器中看到的。

我们的主要挑战 (Our Main Challenge)

The challenge here is how to post data to the WeatherForecast Controller so that it will be automatically deserialized into a WeatherForecast object.

这里的挑战是如何将数据发布到WeatherForecast控制器,以便将其自动反序列化为WeatherForecast对象。

First of all, let's add the most basic Post method to our controller.

首先,让我们向控制器添加最基本的Post方法。

[HttpPost]
public String Post(){
    Console.WriteLine("in post...");
    return "It worked!";
}

First of all, notice that we changed the decorator to [HttpPost] so that this method will fire when the user posts to the URL http://localhost:5001/WeatherForecast.

首先,请注意,我们将装饰器更改为[HttpPost]以便当用户发布到URL http:// localhost:5001 / WeatherForecast时,此方法将触发。

默认过帐方法 (Default Post Method)

This internal method name is Post() but externally there is no action (method name) shown so that means when the user posts directly to the Controller, this is the default action (method that will run) which will occur.

此内部方法名称为Post()但在外部没有显示任何操作(方法名称),因此这意味着当用户直接发布到Controller ,这是将发生的默认操作(将运行的方法)。

There is a way to provide an external name that can then be supplied on the WeatherForecast controller URL and I will show you that in a moment.

有一种方法可以提供一个外部名称,然后可以在WeatherForecast控制器URL上提供该名称,稍后我将向您展示。

次要挑战:客户端帖子创建 (Secondary Challenge: Client Side Post Creation)

Now, we have the challenge of testing the Post() method on the WeatherForecast controller. Since we can no longer use the browser just to navigate to the URL (simple HTTP Get), we need some other way to invoke an HTTP Post from the client.

现在,我们面临着在WeatherForecast控制器上测试Post()方法的挑战。 由于我们不再能够仅使用浏览器导航到URL(简单的HTTP Get ),因此我们需要其他方法从客户端调用HTTP Post

第一次最简单的后期测试 (First Easiest Post Test)

The first and probably easiest way to do a Post to the controller is to download PostMan and set it up. There are other tools, but PostMan is probably the easiest one and it is free.

向控制器执行Post的第一种也是最简单的方法是下载PostMan并进行设置。 还有其他工具,但是PostMan可能是最简单的工具,并且是免费的。

Go to https://www.postman.com/downloads/^, get the free utility and install it for your system.

转到https://www.postman.com/downloads/^ ,获得免费的实用程序并为您的系统安装它。

Once you do and you start it up, we can try posting to our controller.

完成并启动之后,我们可以尝试将其发布到我们的控制器。

Walkthru:邮递员请求 (Walkthru: PostMan Request)

The PostMan User Interface is a bit jumbled but it's easy enough to create a new request and I will walk you through it.

PostMan用户界面有些混乱,但是创建一个新请求很容易,我将逐步引导您。

创建一个新请求 (Create a New Request)

The first thing you want to do is create a new request. To do that, you can choose the [New] button and choose [Request] when the menu appears. Or, you can click the [Create a Request] option. Both of these are shown highlighted in red, in the next image.

您要做的第一件事是创建一个新请求。 为此,您可以选择[ 新建 ]按钮,然后在菜单出现时选择[ 请求 ]。 或者,您可以单击[ 创建请求 ]选项。 在下一个图像中,这两个都以红色突出显示。

postman main UI

Once you choose one of those options, you will see a new form. In the image, you can see that I've also dropped the list of HTTP Actions to show you that is where you can select which one you will use when submitting the request. First, we'll try the simple Get.

选择这些选项之一后,您将看到一个新表格。 在图像中,您可以看到我还删除了HTTP操作列表,以向您显示可以在其中选择提交请求时使用的HTTP操作。 首先,我们将尝试简单的Get

new postman request

PostMan:配置更改 (PostMan: Configuration Change)

However, before we make our first request, you need to make one change to the PostMan default settings. If you do not, then all of your requests will fail because PostMan does not support self-signed certificates.

但是,在我们发出第一个请求之前,您需要对PostMan默认设置进行一次更改。 如果您不这样做,则所有请求都将失败,因为PostMan不支持自签名证书。

If you do not change the setting, then you will see an error like the following (notice blue highlighted text for error).

如果您不更改设置,则将看到类似以下的错误(请注意蓝色突出显示的错误文本)。

HTTPS:不支持自签名证书 (HTTPS: Self-signed Certificates Not Supported)

postman error on certificate

To fix that, you simply go to File...Settings... in PostMan and turn off the option highlighted in red (shown here still turned on) - SSL certificate verification.

要解决此问题,只需在PostMan中转到“ 文件 ... 设置 ...”,然后关闭以红色突出显示的选项(此处显示为打开状态)-SSL证书验证。

turn off certificate verification

Once you do that and close the Settings window, you can proceed and it will work.

完成此操作并关闭“ 设置”窗口后,即可继续进行,它将起作用。

Go ahead and select the Get command from the drop list.

继续,然后从下拉列表中选择“ Get命令。

Next, add the following URL and then press <ENTER> or click the [Send] button.

接下来,添加以下URL,然后按<ENTER>或单击[ 发送 ]按钮。

Once you do that, you'll see similar results to what we saw before (in the browser), but just formatted in the way PostMan formats things.

完成此操作后,您将看到与以前(在浏览器中)看到的结果类似的结果,但只是以PostMan格式化内容的方式进行了格式化。

postman get results

Keep in mind that was the result of calling the default Get() action on the WeatherForecast controller. I mention this as a way to remind you that we did not add any action name (specific) method on the URL.

请记住,这是在WeatherForecast控制器上调用默认的Get()操作的结果。 我提到这一点是为了提醒您,我们没有在URL上添加任何操作名称(特定)方法。

发布到WeatherForecastController (Post to WeatherForecastController)

Now, let's simply change the HTTP Verb to Post in PostMan and try again.

现在,让我们简单地将HTTP Verb更改为PostMan中的Post ,然后重试。

Here's the new and very basic result:

这是新的非常基本的结果:

Post result via PostMan

That is all great, but what we want to do is post some JSON to the controller and have it automatically transform the JSON into our domain object (WeatherForecast).

一切都很好,但是我们要做的是将一些JSON发布到控制器,并使其自动将JSON转换为我们的域对象( WeatherForecast )。

发布JSON:尝试1 (Posting JSON: Attempt 1)

The first thing we need to understand is what the target domain object looks like. What properties does it have?

我们需要了解的第一件事是目标域对象的外观。 它有什么特性?

We can take a look at the WeatherForecast class back in VSC.

我们可以回顾一下VSC中的WeatherForecast类。

WeatherForecast类分析 (WeatherForecast Class Analysis)

It's a very simple class. Here's the entire code listing for that class.

这是一个非常简单的课程。 这是该类的完整代码清单。

using System;
 
namespace MainWebAPI
{
    public class WeatherForecast
    {
        public DateTime Date { get; set; }
 
        public int TemperatureC { get; set; }
 
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
 
        public string Summary { get; set; }
    }
}

It's really just made up of four properties (although one of them does run a function to get its value).

它实际上仅由四个属性组成(尽管其中一个确实运行一个函数来获取其值)。

  1. Date

    Date

  2. TemperatureC // (temp in Celsius)

    TemperatureC //(摄氏温度)

  3. TemperatureF // (calculated temp in Fahrenheit)

    TemperatureF //(以华氏TemperatureF计算)

  4. Summary // text-based summary of the weather

    Summary //基于文本的天气摘要

JSON:名称/值对 (JSON: Name / Value Pairs)

Since we know that JSON (JavaScript Object Notation) is simply name value pairs which define an object, we can create our own WeatherForecast (with data) very easily. Here's the one we'll use for our tests.

由于我们知道JSON(JavaScript对象表示法)只是定义对象的名称/值对,因此我们可以非常轻松地创建自己的WeatherForecast (带有数据)。 这是我们将用于测试的一个。

{"Date":"2015-05-03", "TemperatureC":37,"Summary":"Our weather data"}

Notice that since the TemperatureF is calculated from the TemperatureC, I don't even include that property in our JSON.

请注意,由于TemperatureF从计算TemperatureC ,我甚至不包括在我们的JSON财产。

方括号:Think Object-快速JSON摘要 (Brackets: Think Object - Quick JSON Summary)

Here's a quick way to think about what you see in the JSON. The curly brackets indicate the start and end of an object. Each value before a colon indicates a property name and each value after a colon indicates a property value. Each name/value pair are separated by commas. Each property name must match a property in our target class.

这是考虑您在JSON中看到的内容的快速方法。 大括号表示对象的开始和结束。 冒号前面的每个值表示属性名称,冒号后面的每个值表示属性值。 每个名称/值对用逗号分隔。 每个属性名称必须与目标类中的一个属性匹配。

That's it, so let's try it out using PostMan.

就是这样,所以让我们使用PostMan尝试一下。

更改WeatherForecastController发布方法 (Change WeatherForecastController Post Method)

We have to make one change in our default Post() method in our WeatherForecastController. We have to make sure it is expecting to receive a WeatherForecast object.

我们必须在WeatherForecastController中的默认Post()方法中进行一项更改。 我们必须确保它期望收到一个WeatherForecast对象。

Let's open up WeatherForecastController in VSC and make the change.

让我们在VSC中打开WeatherForecastController并进行更改。

We'll also change the method to return an Int32 and we'll return the TemperatureF so that you can see that the value is generated. This also provides us with a somewhat usuable Web API method (though a bit contrived) because you can send in a WeatherForecast object where you know the Celsius temperature and the method will return the temperature in Fahrenheit.

我们还将更改方法以返回Int32并返回TemperatureF以便您可以看到已生成该值。 这也为我们提供了一种有点有用的Web API方法(尽管有些人为地作废),因为您可以在一个WeatherForecast对象中发送您知道摄氏温度的方法,该方法将以华氏温度返回该温度。

Here's the altered default Post() method.

这是更改后的默认Post()方法。

[HttpPost]
public Int32 Post(WeatherForecast wf){
    Console.WriteLine("in post...");
    return wf.TemperatureF;
}

进行更改并运行 (Make Changes and Run)

Once you make those changes, then go back to your console and:

进行了这些更改之后,请返回控制台并执行以下操作:

  1. close the program if it was already running (press CTRL-C to end the session)

    如果程序已经在运行,请关闭它(按CTRL-C结束会话)

  2. build and run the application again -- dotnet run will build and run the app again

    再次构建并运行该应用程序dotnet run将再次构建并运行该应用程序

  3. Copy the JSON we created above

    复制我们在上面创建的JSON
  4. Go back to PostMan

    回到邮递员
  5. Click the [body] tab (see next image)

    单击[ 身体 ]选项卡(见下图)

  6. Select the [raw] (next image) radio button

    选择[ raw ](下一个图像)单选按钮

  7. Paste the JSON into the editor area.

    将JSON粘贴到编辑器区域。
  8. Click the [Send] button.

    点击[ 发送 ]按钮。

When you do all of those steps, you will see the following result (error). Note: I used one image to show multiple steps and the result.

完成所有这些步骤后,您将看到以下结果(错误)。 注意 :我使用一张图像来显示多个步骤和结果。

postman setup and error result

错误说明 (Error Explanation)

It's a bit confusing, but that bottom portion is the result after posting our JSON to the Controller. We didn't get the expected response (TemperatureF), but instead we got some JSON that is describing the problem. It's difficult to tell that an error even occurred and where the error occurred.

这有点令人困惑,但是最下面的部分是将JSON发布到Controller之后的结果。 我们没有得到预期的响应( TemperatureF ),但是我们得到了一些描述问题的JSON。 很难说出一个错误甚至发生了错误。

Console.WriteLine of Post()方法未运行 (Console.WriteLine of Post() Method Doesn't Run)

Keep in mind that our default WeatherForecastController has a Console.WriteLine() call that attempts to output a message. That should output some text to our console window where the application is running, but if you look, there is no output. That provides us with a clue that our method never ran.

请记住,我们的默认WeatherForecastController具有一个Console.WriteLine()调用,它试图输出一条消息。 这应该在运行应用程序的控制台窗口中输出一些文本,但是如果您查看的话,将没有输出。 这为我们提供了一种方法永远不会运行的线索。

不支持的媒体类型 (Unsupported Media Type)

The real clue to what happened is the Error 415 and the message "unsupported media type". It is still cryptic though and if you're just starting out, you'll really wonder what it all means. After much searching and reading, you'll find that it means that the server doesn't know what type of data we are posting to it and it doesn't like that.

发生错误的真正线索是错误415和消息“不支持的媒体类型”。 但是,它仍然是一个神秘的事物,如果您刚刚开始,那么您真的会想知道这意味着什么。 经过大量搜索和阅读之后,您会发现这意味着服务器不知道我们要向其发布什么类型的数据,并且也不喜欢这样。

使用HTTP标头解决问题 (Fix the Problem with an HTTP Header)

We can tell the server the type of data we are sending by adding an HTTP Header to our Post action.

通过将HTTP标头添加到Post操作中,我们可以告诉服务器正在发送的数据类型。

The server wants to know what type of data you are sending so it can properly use the data. Let's go add the proper HTTP Header to our PostMan Post action and try again.

服务器想知道您要发送的数据类型,以便可以正确使用数据。 让我们将适当的HTTP标头添加到PostMan Post操作中,然后重试。

HTTP Headers: Name / Value Pairs

HTTP标头:名称/值对

HTTP Headers are metadata (data sent with the actual data to describe the data) which are sent along with the data. To add a name / value pair to the PostMan headers, we just need to:

HTTP标头是与数据一起发送的元数据(与实际数据一起发送的数据,用于描述数据)。 要将名称/值对添加到PostMan标头中,我们只需要:

  1. select the Headers tab (see next image)

    选择“标题”选项卡(请参见下图)
  2. add a new header named : Content-Type (type this in the list under Key (same as Name))

    添加一个名为Header的新标题: Content-Type (在“键(与名称相同)”下的列表中键入该标题)

  3. add a new value for the added Key: application/json

    为添加的键添加一个新值: application/json

That Key and value are both predefined values that are described by the HTTP specification which the server will understand.

该Key和value都是服务器将理解的HTTP规范描述的预定义值。

adding header to PostMan

Now, when you post again, the server will understand that incoming content is JSON and should be handled as JSON.

现在,当您再次发布时,服务器将理解传入的内容是JSON,应将其作为JSON处理。

After you've made those changes, go ahead and click the [Send] button in PostMan again and this time, you will get a valid result. 98 Fahrenheit is the same temperature as 37 Celsius (the value we sent into the WeatherForecastController in our JSON).

进行了这些更改之后,继续并再次单击PostMan中的[ 发送 ]按钮,这一次,您将获得有效的结果。 98华氏温度与37摄氏度(我们在JSON中发送到WeatherForecastController的值)相同。

TemperatureF returned successfully

You can also tell that the WeatherForecastController Post() method did indeed run because back in your console window, there is some output from the call to Console.WriteLine():

您还可以告诉我们WeatherForecastController Post()方法确实在运行,因为回到控制台窗口后,对Console.WriteLine()的调用有一些输出:

console output

自动转换为域对象:太神奇了! (Automatic Convert to Domain Object: Amazing!)

Also, think about how amazing it is that underlying .NET Core Web API automatically converted our JSON into our domain object (WeatherForecast).

此外,请考虑一下底层的.NET Core Web API将我们的JSON自动转换为我们的域对象( WeatherForecast )的惊人程度。

You can tell that it did that automatically because our default Post() method simply takes a parameter of type WeatherForecast and we referenced a property of the object in our return statement:

您可以说它是自动完成的,因为我们的默认Post()方法仅采用WeatherForecast类型的参数,并且我们在return语句中引用了该对象的属性:

return wf.TemperatureF;

总结第1部分 (Wrapping Up Part 1)

I hope you found Part 1 of this article series instructional and that it revealed a few of the trickier elements (HTTP Headers, HTTP Post and using PostMan) in a clear way.

我希望您能从本系列文章的第1部分中获得指导,并以清晰的方式揭示了一些棘手的元素(HTTP标头,HTTP Post和使用PostMan)。

However, since this article is already so long, I've decided to put the rest of the article in Part 2.

但是,由于本文已经很长了,因此我决定将本文的其余部分放在第2部分中

Now that we understand that we need...

现在我们知道我们需要...

  1. JSON data added to the Post body

    JSON数据已添加到Post正文

  2. Special Content-Type header added to the Post action

    特殊Content-Type标头已添加到Post操作中

...that will make it much easier to understand how we are going to use AJAX (XMLHttpRequest object) via JavaScript to post data to our Web API controller.

...这将使我们更容易理解如何通过JavaScript使用AJAX( XMLHttpRequest对象)将数据发布到我们的Web API控制器。

使用代码 (Using the Code)

  1. Download the zip file.

    下载压缩文件。
  2. Unzip to your Dev directory (there is an outer folder named MainWebAPI that contains all files and subfolders).

    解压缩到Dev目录(有一个名为MainWebAPI的外部文件夹,其中包含所有文件和子文件夹)。

  3. Open console and change directory to \MainWebAPI.

    打开控制台并将目录更改为\ MainWebAPI

  4. Run command /> dotnet run.

    运行命令/> dotnet run

  5. The application will build and start the web server.

    该应用程序将构建并启动Web服务器。

翻译自: https://www.codeproject.com/Articles/5268373/NET-Core-Web-API-The-Least-You-Need-To-Know-Part-1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值