GVKun编程网logo

Action Results in Web API 2

1

在本文中,我们将给您介绍关于ActionResultsinWebAPI2的详细内容,此外,我们还将为您提供关于ActionButton有什么好处?ActionButton可自定义哪些操作?、Actio

在本文中,我们将给您介绍关于Action Results in Web API 2的详细内容,此外,我们还将为您提供关于Action Button有什么好处?Action Button可自定义哪些操作?、Action 的 Alpha 用户无法访问 Google 助理目录列表或 Action、ActiveMQ In Action 第三章 ActiveMQ In Action 示例 前言、Android Action Bar(Sherlock Action Bar) – 将下拉微调器一直放在右侧的知识。

本文目录一览:

Action Results in Web API 2

Action Results in Web API 2

https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results

This topic describes how ASP.NET Web API converts the return value from a controller action into an HTTP response message.

A Web API controller action can return any of the following:

  1. void
  2. HttpResponseMessage
  3. IHttpActionResult
  4. Some other type

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response.

Return type How Web API creates the response
void Return empty 204 (No Content)
HttpResponseMessage Convert directly to an HTTP response message.
IHttpActionResult Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.
Other type Write the serialized return value into the response body; return 200 (OK).

The rest of this topic describes each option in more detail.

void

If the return type is void, Web API simply returns an empty HTTP response with status code 204 (No Content).

Example controller:

public class ValuesController : ApiController
    {
        [HttpGet]
        public void Post()
        {
        }
    }

request

GET http://localhost/Chuck_WebApi/api/values/post HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 204 No Content
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 17 Jan 2019 10:04:57 GMT

 

HttpResponseMessage

If the action returns an HttpResponseMessage, Web API converts the return value directly into an HTTP response message, using the properties of the HttpResponseMessage object to populate the response.

This option gives you a lot of control over the response message. For example, the following controller action sets the Cache-Control header.

需要把路由从默认的routeTemplate: "api/{controller}/{id}"调整为routeTemplate: "api/{controller}/{action}/{id}"

public HttpResponseMessage Get()
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
            response.Content = new StringContent("hello", Encoding.Unicode);
            response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                MaxAge = TimeSpan.FromMinutes(20)
            };
            return response;
        }

request

GET http://localhost/Chuck_WebApi/api/values/get HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 200 OK
Cache-Control: max-age=1200
Content-Length: 10
Content-Type: text/plain; charset=utf-16
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 17 Jan 2019 10:25:14 GMT

hello

If you pass a domain model to the CreateResponse method, Web API uses a media formatter to write the serialized model into the response body.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection

https://autofaccn.readthedocs.io/en/latest/integration/webapi.html

 此处代码的前提是,在项目启动的时候,使用了Autofac.WebApi2初始化GlobalConfiguration.Configuration.DependencyResolver

public HttpResponseMessage Get2()
        {
            var dependencyResolver = GlobalConfiguration.Configuration.DependencyResolver;
            var controller = dependencyResolver.GetService(typeof(ProductsController));
            ProductsController productsController = controller as ProductsController;
            //productsController.ControllerContext //might need set value here

            // Get a list of products from a database.
            IEnumerable<Product> products = productsController.GetAllProducts();

            // Write the list to the response body.
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
            return response;
        }

Web API uses the Accept header in the request to choose the formatter. For more information, see Content Negotiation.

request

GET http://localhost/Chuck_WebApi/api/values/get2 HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 17 Jan 2019 11:13:15 GMT
Content-Length: 182

[{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

 

IHttpActionResult

The IHttpActionResult interface was introduced in Web API 2. Essentially, it defines an HttpResponseMessage factory. Here are some advantages of using the IHttpActionResult interface:

  • Simplifies unit testing your controllers.
  • Moves common logic for creating HTTP responses into separate classes.
  • Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.

IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance.

public interface IHttpActionResult
{
    Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}

If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.

Here is a simple implementaton of IHttpActionResult that creates a plain text response:

public class TextResult : IHttpActionResult
    {
        string _value;
        HttpRequestMessage _request;

        public TextResult(string value, HttpRequestMessage request)
        {
            _value = value;
            _request = request;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage()
            {
                Content = new StringContent(_value),
                RequestMessage = _request
            };
            return Task.FromResult(response);
        }
    }

 

Example controller action:

public IHttpActionResult Get3()
        {
            return new TextResult("hello", Request);
        }

request

GET http://localhost/Chuck_WebApi/api/values/get3 HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 5
Content-Type: text/plain; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Jan 2019 02:19:02 GMT

hello

More often, you will use the IHttpActionResult implementations defined in the System.Web.Http.Results namespace. The ApiController class defines helper methods that return these built-in action results.

https://docs.microsoft.com/en-us/previous-versions/aspnet/dn314678(v=vs.118)    系统内定的一些IHttpActionResult 的实现

ApiController 本身也内置了一部分的方法,来返回对应的实现

BadRequestErrorMessageResult

UnauthorizedResult

 

In the following example, if the request does not match an existing product ID, the controller calls ApiController.NotFound to create a 404 (Not Found) response.

Otherwise, the controller calls ApiController.OK, which creates a 200 (OK) response that contains the product.

public IHttpActionResult Get4(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound(); // Returns a NotFoundResult
            }
            return Ok(product);  // Returns an OkNegotiatedContentResult
        }

request1

GET http://localhost/Chuck_WebApi/api/values/get4/3 HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response1

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Jan 2019 02:36:31 GMT
Content-Length: 60

{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}

request2

GET http://localhost/Chuck_WebApi/api/values/get4/4 HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response2

HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Jan 2019 02:50:06 GMT
Content-Length: 0

Other Return Types

For all other return types, Web API uses a media formatter to serialize the return value.

Web API writes the serialized value into the response body.

The response status code is 200 (OK).

public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

 

A disadvantage of this approach is that you cannot directly return an error code, such as 404.

However, you can throw an HttpResponseException for error codes.

For more information, see Exception Handling in ASP.NET Web API.

Web API uses the Accept header in the request to choose the formatter. For more information, see Content Negotiation.

request

GET http://localhost/Chuck_WebApi/api/products/getallproducts HTTP/1.1
User-Agent: Fiddler
Host: localhost
Content-Length: 0

response

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Jan 2019 03:10:56 GMT
Content-Length: 182

[{"Id":1,"Name":"Tomato Soup","Category":"Groceries","Price":1.0},{"Id":2,"Name":"Yo-yo","Category":"Toys","Price":3.75},{"Id":3,"Name":"Hammer","Category":"Hardware","Price":16.99}]

 

 

 

 

 

Action Button有什么好处?Action Button可自定义哪些操作?

Action Button有什么好处?Action Button可自定义哪些操作?

你觉得iPhone手机上的物理静音按钮好用吗?

消息称 iPhone 15 Pro 和 iPhone 15 Ultra(或叫 iPhone 15 Pro Max)两款机型的机身侧面将弃用自 2007 年以来的静音拨片,改为类似于 Apple Watch Ultra 的 Action Button了。具体来说就是,iPhone 15 Pro、iPhone 15 Pro Max将取消实体音量键和侧面静音开关,却而代之的是细长整体按键来调整音量,并且会采用固态设计,有触感反馈和模拟物理按键的触感——Action Button。

Action Button的优点在于,允许用户根据自身偏好进行各种自定义。不少人认可Action Button,觉得习惯了上述设计后,使用起来非常顺手。

以下为网友分享的Action Button 可以自定义的选项汇总:

切换响铃和静音状态

启用 / 禁用勿扰模式

启用 / 禁用闪光灯

启用 / 禁用省电模式

切换浅色 / 深色主题

启用 / 禁用旋转锁定

显示主屏幕

显示锁屏界面

打开控制中心

打开通知中心

打开相机

截图

录屏

运行某条捷径

显示多任务视图

显示 App Library

启动听歌识曲服务 Shazam

VoiceOver

启动指南针

更改背景音乐

这些 Action Button 的功能目前大部分可以通过 Back Tap 功能来实现。该功能于 iOS 14 中引入,可以通过敲击 iPhone 背面来触发特定操作。

想使用此功能,大家可以进入“设置” → “辅助功能” → “辅助触摸” → “回退操作”下进行设置。

Action 的 Alpha 用户无法访问 Google 助理目录列表或 Action

Action 的 Alpha 用户无法访问 Google 助理目录列表或 Action

我从昨天开始就有同样的问题。不仅是 alpha 测试人员,除非我在设备上启用测试,否则我的开发人员帐户无法访问我的操作。即使我尝试删除它们并重新添加它们,我的旧/现有 Alpha 测试人员也无法访问该操作。

我目前唯一发现的是,如果您将新测试帐户(而不是旧帐户)添加到白名单,这些新测试人员可以照常访问该操作。

,

行动小组似乎在过去几个小时内解决了这个问题。问题解决了,Alpha 用户可以像以前一样调用和访问我们的 Action。我们希望 Dialogflow 与 Actions on Google 的集成继续得到支持,同时开发者考虑按照自己的节奏迁移到 Actions Builder。

ActiveMQ In Action 第三章 ActiveMQ In Action 示例 前言

ActiveMQ In Action 第三章 ActiveMQ In Action 示例 前言

本章包含
■本书所有示例的用户案例简介

■使用 Maven 来编译和运行示例

■如何使用 ActiveMQ 的示例应用程序

ActiveMQ 提供 JMS 规范的所有特性并在此基础上添加了许多强大功能。这是如图 3.1 所示,通过本书剩余部分将讨论这些功能。为了最好的展示这些特性,创建了两个新示例,仿照真实的业务领域。相对于分散的 ActiveMQ 示例,这些示例能以更完整和简单的方式说明 ActiveMQ 特性。

/////////////////////////////////////////F3.1

其中一个例子是基于一个股票投资组合,另一个是基于一个工作队列。这两个例子的使用范围不局限于 ActiveMQ。用例为每个例子做简要介绍,接下来更深层次地讨论如何使用它们。你可以随时回到本章对这些例子做一些回顾,如果你需要更深入理解这些例子。

股票投资组合展示了发布 / 订阅消息传递域。出版商为感兴趣的用户广播股票价格信息。消息被发布到被称为主题的 JMS 目的地,客户端通过主动订阅来接收消息。这个模型中,代理为每个订阅者提供消息时不需要轮询消息。每个活跃用户接收自己的发布到主题的消息副本。通过主题,发布者和订阅者实现解耦。除非使用持久订阅,订阅者必须保持活跃为了接收消息发布者发布到主题的消息。通过 pub/sub 域,给定目的地的每条消息的副本将交付给所有的主题订阅者。

工作队列演示点对点消息传递域 (PTP)。消息生产者将工作消息发送到一个 JMS 队列,也是从此,消息消费者接收工作消息进行处理。点对点域中,对生产者和消费者没有同时在线的要求。队列保存消息,直到消费者可以得到它们。当有可用消费者时,消息将发送给所用消费者,但不会有两个消费者接收到相同的消息。点对点域中,给定目的地的消息以循环的方式交付给队列消费者。

每个示例不仅关注不同的消息传递域,也使用不同的用例。此外,尽管本章后面每个例子的图绘咋看起来几乎一模一样,这两者之间的重要区别在于两个消息传递域。股票投资组合的例子为发布 / 订阅消息传递使用主题,而作业队列的例子为点对点消息使用队列。这些例子的来源是现成的,可以通过以下 URL 网上下载:http://manning.com/snyder/activemq-in-action-examples-src.zip。

在本章中,首先我们将下载并安装 Maven 来编译和运行示例。这完成后,我们将回顾每个示例,演示各自的行为。完成这些练习之后,你将对例子有了一定了解并在本书中能够认出它们,进而理解它们是如何展示 ActiveMQ 特性的。

Android Action Bar(Sherlock Action Bar) – 将下拉微调器一直放在右侧

Android Action Bar(Sherlock Action Bar) – 将下拉微调器一直放在右侧

有没有办法改变操作栏中下拉微调器的位置?

我找到了旋转器下拉的这种风格:

    

关于Action Results in Web API 2的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Action Button有什么好处?Action Button可自定义哪些操作?、Action 的 Alpha 用户无法访问 Google 助理目录列表或 Action、ActiveMQ In Action 第三章 ActiveMQ In Action 示例 前言、Android Action Bar(Sherlock Action Bar) – 将下拉微调器一直放在右侧的相关信息,请在本站寻找。

本文标签: