我正在寻找在我的 .NET Core Web API 控制器中返回带有 HTTP 状态代码的 JSON 的正确方法。我曾经这样使用它:
public IHttpActionResult GetResourceData()
{
return this.Content(HttpStatusCode.OK, new { response = "Hello"});
}
这是在 4.6 MVC 应用程序中,但现在使用 .NET Core 我似乎没有这个 IHttpActionResult
我有 ActionResult
并像这样使用:
public ActionResult IsAuthenticated()
{
return Ok(Json("123"));
}
但是服务器的响应很奇怪,如下图所示:
https://i.stack.imgur.com/DpSlo.png
我只希望 Web API 控制器返回带有 HTTP 状态代码的 JSON,就像我在 Web API 2 中所做的那样。
CreatedAtRoute
方法等。
以 JsonResult
响应的最基本版本是:
// GET: api/authors
[HttpGet]
public JsonResult Get()
{
return Json(_authorRepository.List());
}
但是,这对您的问题没有帮助,因为您无法明确处理自己的响应代码。
控制状态结果的方法是您需要返回一个 ActionResult ,然后您可以在其中利用 StatusCodeResult 类型。
例如:
// GET: api/authors/search?namelike=foo
[HttpGet("Search")]
public IActionResult Search(string namelike)
{
var result = _authorRepository.GetByNameSubstring(namelike);
if (!result.Any())
{
return NotFound(namelike);
}
return Ok(result);
}
请注意,上述两个示例均来自 Microsoft 文档中的一个很好的指南:Formatting Response Data
额外的东西
我经常遇到的问题是,我希望对我的 WebAPI 进行更精细的控制,而不是仅仅使用 VS 中“新项目”模板中的默认配置。
让我们确保您掌握了一些基础知识...
第 1 步:配置您的服务
为了让您的 ASP.NET Core WebAPI 响应 JSON 序列化对象以及对状态代码的完全控制,您应该首先确保已将 AddMvc()
服务包含在您的 ConfigureServices
方法中,通常在Startup.cs
。
重要的是要注意 AddMvc() 将自动包含 JSON 的输入/输出格式化程序以及响应其他请求类型。
如果您的项目需要完全控制并且您希望严格定义您的服务,例如您的 WebAPI 如何处理各种请求类型,包括 application/json
,而不响应其他请求类型(例如标准浏览器请求),您可以使用以下代码手动定义它:
public void ConfigureServices(IServiceCollection services)
{
// Build a customized MVC implementation, without using the default AddMvc(), instead use AddMvcCore().
// https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc/MvcServiceCollectionExtensions.cs
services
.AddMvcCore(options =>
{
options.RequireHttpsPermanent = true; // does not affect api requests
options.RespectBrowserAcceptHeader = true; // false by default
//options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
//remove these two below, but added so you know where to place them...
options.OutputFormatters.Add(new YourCustomOutputFormatter());
options.InputFormatters.Add(new YourCustomInputFormatter());
})
//.AddApiExplorer()
//.AddAuthorization()
.AddFormatterMappings()
//.AddCacheTagHelper()
//.AddDataAnnotations()
//.AddCors()
.AddJsonFormatters(); // JSON, or you can build your own custom one (above)
}
您会注意到,我还提供了一种添加您自己的自定义输入/输出格式化程序的方法,以防您可能想要响应另一种序列化格式(protobuf、thrift 等)。
上面的代码块大部分是 AddMvc()
方法的副本。但是,我们通过定义每一项服务来自行实现每项“默认”服务,而不是使用带有模板的预发布服务。我已经在代码块中添加了存储库链接,或者您可以查看 AddMvc()
from the GitHub repository.。
请注意,有一些指南会尝试通过“撤消”默认设置来解决这个问题,而不是一开始就不实施它......如果你考虑到我们现在正在使用开源,这是多余的工作,糟糕的代码,坦率地说,这是一个很快就会消失的旧习惯。
第 2 步:创建控制器
我将向您展示一个非常直截了当的问题,只是为了解决您的问题。
public class FooController
{
[HttpPost]
public async Task<IActionResult> Create([FromBody] Object item)
{
if (item == null) return BadRequest();
var newItem = new Object(); // create the object to return
if (newItem != null) return Ok(newItem);
else return NotFound();
}
}
第 3 步:检查您的 Content-Type 并接受
您需要确保您的 request 中的 Content-Type
和 Accept
标头设置正确。在您的情况下 (JSON),您需要将其设置为 application/json
。
如果您希望 WebAPI 默认以 JSON 响应,无论请求标头指定什么,您都可以通过几种方式来实现。
方式 1 如我之前推荐的文章 (Formatting Response Data) 所示,您可以在 Controller/Action 级别强制使用特定格式。我个人不喜欢这种方法......但这里是为了完整性:
强制使用特定格式 如果您想限制特定操作的响应格式,您可以应用 [Produces] 过滤器。 [Produces] 过滤器指定特定操作(或控制器)的响应格式。像大多数过滤器一样,这可以应用于操作、控制器或全局范围。 [Produces("application/json")] public class AuthorsController [Produces] 过滤器将强制 AuthorsController 中的所有操作返回 JSON 格式的响应,即使为应用程序配置了其他格式化程序并且客户端提供了 Accept 标头请求不同的可用格式。
方式 2 我的首选方法是让 WebAPI 以请求的格式响应所有请求。但是,如果它不接受请求的格式,则回退到默认值(即 JSON)
首先,您需要在您的选项中注册它(我们需要修改默认行为,如前所述)
options.RespectBrowserAcceptHeader = true; // false by default
最后,通过简单地重新排序服务构建器中定义的格式化程序列表,Web 主机将默认使用您位于列表顶部的格式化程序(即位置 0)。
可在此 .NET Web Development and Tools Blog entry 中找到更多信息
您已经为最常见的状态代码预定义了方法。
Ok(result) 返回 200 和响应
CreatedAtRoute 返回 201 + 新资源 URL
未找到返回 404
BadRequest 返回 400 等。
有关所有方法的列表,请参阅 BaseController.cs
和 Controller.cs
。
但是,如果您真的坚持可以使用 StatusCode
来设置自定义代码,但您真的不应该这样做,因为它会降低代码的可读性,并且您必须重复代码来设置标题(例如 CreatedAtRoute
)。
public ActionResult IsAuthenticated()
{
return StatusCode(200, "123");
}
JSON
由 Json()
方法创建的 ActionResult
。它不直接包含“123”字符串。
Json(...)
并将字符串传递给 StatusCode
使用 ASP.NET Core 2.0,从 Web API
(与 MVC 统一并使用相同的基类 Controller
)返回对象的理想方式是
public IActionResult Get()
{
return new OkObjectResult(new Item { Id = 123, Name = "Hero" });
}
请注意
它返回 200 OK 状态码(它是 ObjectResult 的 Ok 类型) 它进行内容协商,即它将根据请求中的 Accept 标头返回。如果 Accept: application/xml 在请求中发送,它将作为 XML 返回。如果未发送任何内容,则默认为 JSON。
如果它需要发送带有特定状态代码,请改用 ObjectResult
或 StatusCode
。两者都做同样的事情,并支持内容协商。
return new ObjectResult(new Item { Id = 123, Name = "Hero" }) { StatusCode = 200 };
return StatusCode( 200, new Item { Id = 123, Name = "Hero" });
甚至更细粒度的 ObjectResult:
Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection myContentTypes = new Microsoft.AspNetCore.Mvc.Formatters.MediaTypeCollection { System.Net.Mime.MediaTypeNames.Application.Json };
String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
return new ObjectResult(hardCodedJson) { StatusCode = 200, ContentTypes = myContentTypes };
如果您特别想以 JSON 格式返回,有几种方法
//GET http://example.com/api/test/asjson
[HttpGet("AsJson")]
public JsonResult GetAsJson()
{
return Json(new Item { Id = 123, Name = "Hero" });
}
//GET http://example.com/api/test/withproduces
[HttpGet("WithProduces")]
[Produces("application/json")]
public Item GetWithProduces()
{
return new Item { Id = 123, Name = "Hero" };
}
请注意
两者都以两种不同的方式强制执行 JSON。两者都忽略了内容协商。第一种方法使用特定的序列化器 Json(object) 强制执行 JSON。第二种方法通过使用 Produces() 属性(它是一个 ResultFilter)和 contentType = application/json 来做同样的事情
在 the official docs 中阅读有关它们的更多信息。了解filters here。
示例中使用的简单模型类
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
我想出的最简单的方法是:
var result = new Item { Id = 123, Name = "Hero" };
return new JsonResult(result)
{
StatusCode = StatusCodes.Status201Created // Status code here
};
这是我最简单的解决方案:
public IActionResult InfoTag()
{
return Ok(new {name = "Fabio", age = 42, gender = "M"});
}
或者
public IActionResult InfoTag()
{
return Json(new {name = "Fabio", age = 42, gender = "M"});
}
我在这里找到了很棒的答案,我还尝试了这个返回语句,参见 StatusCode(whatever code you wish)
,它成功了!!!
return Ok(new {
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo,
username = user.FullName,
StatusCode = StatusCode(200)
});
而不是使用枚举使用 404/201 状态代码
public async Task<IActionResult> Login(string email, string password)
{
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
{
return StatusCode((int)HttpStatusCode.BadRequest, Json("email or password is null"));
}
var user = await _userManager.FindByEmailAsync(email);
if (user == null)
{
return StatusCode((int)HttpStatusCode.BadRequest, Json("Invalid Login and/or password"));
}
var passwordSignInResult = await _signInManager.PasswordSignInAsync(user, password, isPersistent: true, lockoutOnFailure: false);
if (!passwordSignInResult.Succeeded)
{
return StatusCode((int)HttpStatusCode.BadRequest, Json("Invalid Login and/or password"));
}
return StatusCode((int)HttpStatusCode.OK, Json("Sucess !!!"));
}
ASP.NET Core Web API 中的控制器操作返回类型 02/03/2020
6分钟阅读+2
斯科特·艾迪 Link
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<Product> GetById(int id)
{
if (!_repository.TryGetProduct(id, out var product))
{
return NotFound();
}
return product;
}
[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<Product>> CreateAsync(Product product)
{
if (product.Description.Contains("XYZ Widget"))
{
return BadRequest();
}
await _repository.AddProductAsync(product);
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
请参考以下代码,您可以使用不同类型的 JSON 管理多个状态代码
public async Task<HttpResponseMessage> GetAsync()
{
try
{
using (var entities = new DbEntities())
{
var resourceModelList = entities.Resources.Select(r=> new ResourceModel{Build Your Resource Model}).ToList();
if (resourceModelList.Count == 0)
{
return this.Request.CreateResponse<string>(HttpStatusCode.NotFound, "No resources found.");
}
return this.Request.CreateResponse<List<ResourceModel>>(HttpStatusCode.OK, resourceModelList, "application/json");
}
}
catch (Exception ex)
{
return this.Request.CreateResponse<string>(HttpStatusCode.InternalServerError, "Something went wrong.");
}
}
我在我的 Asp Net Core Api 应用程序中所做的是创建一个从 ObjectResult 扩展的类,并提供许多构造函数来自定义内容和状态代码。然后我所有的 Controller 操作都使用其中一个适当的构造函数。您可以在以下位置查看我的实现:https://github.com/melardev/AspNetCoreApiPaginatedCrud
和
https://github.com/melardev/ApiAspCoreEcommerce
这是该类的外观(请访问我的仓库获取完整代码):
public class StatusCodeAndDtoWrapper : ObjectResult
{
public StatusCodeAndDtoWrapper(AppResponse dto, int statusCode = 200) : base(dto)
{
StatusCode = statusCode;
}
private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, string message) : base(dto)
{
StatusCode = statusCode;
if (dto.FullMessages == null)
dto.FullMessages = new List<string>(1);
dto.FullMessages.Add(message);
}
private StatusCodeAndDtoWrapper(AppResponse dto, int statusCode, ICollection<string> messages) : base(dto)
{
StatusCode = statusCode;
dto.FullMessages = messages;
}
}
注意你用你的对象替换 dto 的 base(dto),你应该很高兴。
我得到了这个工作。我的大问题是我的 json 是一个字符串(在我的数据库中......而不是特定/已知类型)。
好的,我终于让它工作了。
////[Route("api/[controller]")]
////[ApiController]
////public class MyController: Microsoft.AspNetCore.Mvc.ControllerBase
////{
//// public IActionResult MyMethod(string myParam) {
string hardCodedJson = "{}";
int hardCodedStatusCode = 200;
Newtonsoft.Json.Linq.JObject job = Newtonsoft.Json.Linq.JObject.Parse(hardCodedJson);
/* "this" comes from your class being a subclass of Microsoft.AspNetCore.Mvc.ControllerBase */
Microsoft.AspNetCore.Mvc.ContentResult contRes = this.Content(job.ToString());
contRes.StatusCode = hardCodedStatusCode;
return contRes;
//// } ////end MyMethod
//// } ////end class
我碰巧在asp.net core 3.1上
#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
//C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.1.0\ref\netcoreapp3.1\Microsoft.AspNetCore.Mvc.Core.dll
我从这里得到提示 :: https://www.jianshu.com/p/7b3e92c42b61
我找到的最干净的解决方案是在 Startup.cs 的 ConfigureServices 方法中设置以下内容(在我的情况下,我希望剥离 TZ 信息。我总是希望看到用户看到的日期时间)。
services.AddControllers()
.AddNewtonsoftJson(o =>
{
o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
});
DateTimeZoneHandling 选项是 Utc、未指定、本地或 RoundtripKind
我仍然想找到一种能够在每次通话的基础上请求这个的方法。
就像是
static readonly JsonMediaTypeFormatter _jsonFormatter = new JsonMediaTypeFormatter();
_jsonFormatter.SerializerSettings = new JsonSerializerSettings()
{DateTimeZoneHandling = DateTimeZoneHandling.Unspecified};
return Ok("Hello World", _jsonFormatter );
我正在从 ASP.NET 转换,并在那里使用了以下辅助方法
public static ActionResult<T> Ok<T>(T result, HttpContext context)
{
var responseMessage = context.GetHttpRequestMessage().CreateResponse(HttpStatusCode.OK, result, _jsonFormatter);
return new ResponseMessageResult(responseMessage);
}
不定期副业成功案例分享
IActionResult
和return Ok(new {response = "123"});
干杯!RespectBrowserAcceptHeader
在实现使用替代序列化程序或更常见的情况下至关重要。因此,我强调“如果您的项目需要完全控制并且您想严格定义您的服务”,并注意该语句上方突出显示的块引用。