My controller returns a 204 when I do a GET request and I don't find any data.
[Route("user/v1/[controller]")]
public class UserLoginController : Controller
{
[HttpGet]
public async Task<UserLogin> Get(int userId)
{
var userLoginLogic = new UserLoginLogic();
return await userLoginLogic.GetUserLogin(userId);
}
}
This is only for GET requests, POST, PUT, DELETE return a 200 empty response. This messes with my swagger definition which has a response defined for a 200 response, and I would rather be consistent.
The 204 would be fine if I was serving HTML out of this controller but it is for a REST API.
How do I get it to return a 200?
With the new ActionResult<T> in v2.1+ you can also refactor to specifically tell the controller to return Ok 200 using the Ok() helper methods
[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
[HttpGet]
public async Task<ActionResult<UserLogin>> Get(int userId) {
var userLoginLogic = new UserLoginLogic();
var model = await userLoginLogic.GetUserLogin(userId);
return Ok(model);
}
}
however this can be misleading if there is in fact no content to return. Consider using an appropriate response status
[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
[HttpGet]
public async Task<ActionResult<UserLogin>> Get(int userId) {
var userLoginLogic = new UserLoginLogic();
var model = await userLoginLogic.GetUserLogin(userId);
if(model == null) return NotFound(); //404
return Ok(model); //200
}
}
If intent on returning 200 Ok with no content use ControllerBase.Ok() method
Creates a OkResult object that produces an empty Status200OK response.
[Route("user/v1/[controller]")]
public class UserLoginController : Controller {
[HttpGet]
public async Task<ActionResult<UserLogin>> Get(int userId) {
var userLoginLogic = new UserLoginLogic();
var model = await userLoginLogic.GetUserLogin(userId);
if(model == null) return Ok(); //200 with no content
return Ok(model); //200
}
}
Reference Controller action return types in ASP.NET Core Web API:
See:
https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-3.1#special-case-formatters
https://www.colabug.com/2020/0224/7036191/
https://weblog.west-wind.com/posts/2020/Feb/24/Null-API-Responses-and-HTTP-204-Results-in-ASPNET-Core
services.AddControllers(opt => // or AddMvc()
{
// remove formatter that turns nulls into 204 - No Content responses
// this formatter breaks Angular's Http response JSON parsing
opt.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
})
Hi i am developing API's using Web API 2. I know how to add header when using HttpResponseMessage. Now I am using IHttpActionResult.
Below is my sample current code.
return Content(HttpStatusCode.OK, LoginResponse);
How can I add a header when I am returning content?
Whenever I use HttpResponseMessage I will be having request object and I can add header.
Below code I tried in HttpResponseMessage.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Headers.AddCookies(new[] { cookie });
return response;
In this case where can I add header values?
You can continue to use the HttpResponseMessage as you are accustom to and update the header. After which you can use the IHttpActionResult ResponseMessage(HttpResponseMessage) method to convert to IHttpActionResult
Simple example
public class MyApiController : ApiController {
public IHttpActionResult MyExampleAction() {
var LoginResponse = new object();//Replace with your model
var cookie = new CookieHeaderValue("name", "value");//Replace with your cookie
//Create response as usual
var response = Request.CreateResponse(System.Net.HttpStatusCode.OK, LoginResponse);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Headers.AddCookies(new[] { cookie });
//Use ResponseMessage to convert it to IHttpActionResult
return ResponseMessage(response);
}
}
You can create a custom IHttpActionResult which decorates a real one but exposes a way to manipulate the response:
public class CustomResult : IHttpActionResult
{
private readonly IHttpActionResult _decorated;
private readonly Action<HttpResponseMessage> _response;
public CustomResult(IHttpActionResult decorated, Action<HttpResponseMessage> response)
{
_decorated = decorated;
_response = response;
}
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = await _decorated.ExecuteAsync(cancellationToken);
_response(response);
return response;
}
}
Then use this in your action:
return new CustomResult(Content(HttpStatusCode.OK, loginResponse), res => res.Headers.AddCookies(new []{ cookie}));
You can add header by using this code:
HttpContext.Current.Response.AppendHeader("Some-Header", value);
or this
response.Headers.Add("Some-Header", value);
protected HttpResponseMessage CreatedResponse(string routeName, object routeValues)
{
var response = Request.CreateResponse(HttpStatusCode.Created);
var locationUri = Url.Link(routeName, routeValues);
response.Headers.Location = new Uri(locationUri);
return response;
}
Whats the equivalent code in .net Core?
Or a way around it..
Thanks
you need to use Controller.Created method, but now it also requires information about URI:
public IActionResult CreatedResponse(object value)
{
return this.Created(<string uri>, value);
//or
return this.Created(<Uri uri>, value);
}
Actually, in background method creates and returns the CreatedResult object, that is derived from ObjectResult, and fill Location, Value and StatusCode fields. So, as alternative, you may create general ObjectResult response if you don't need to return the URI.
public IActionResult CreatedResponse(object value)
{
return new ObjectResult
{
Value = value,
StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status201Created // 201
};
}
I built upon the other answer, and created an extension method. You will have to return an IActionResult. So if you still want to do it the old fashion way, you can with this:
public static class HttpRequestExtensions
{
public static IActionResult CreateResponse(this HttpRequest request, int status, object content)
{
return new ObjectResult(content)
{
StatusCode = status
};
}
}
And in use:
public IActionResult Patch(long id, [FromBody]JsonPatchDocument<SomeModel> value)
{
//other code here for patching logic
var response = new { Original = modelBefore, Patched = modelAfter };
return Request.CreateResponse(StatusCodes.Status200OK, response);
}
How do I set a cookie when using Web api 2 and odata. I am new to this api and traditionally I used the context.Response but it does not seem to be avaliable here.
This is a part of my controller code:
public async Task<IHttpActionResult> Post(Order Order)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
context.Orders.Add(Order);
await context.SaveChangesAsync();
return Created(Order);
}
If you are using the IHttpActionResult class there's a function within it Task<System.Net.Http.HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
You can use that function to return the HttpResponseMessage and add cookies to the response message.
I would make another class that implements IHttpActionResult similar to this:
public class OrderResult : IHttpActionResult
{
Order _order;
HttpRequestMessage _request;
public OrderResult(Order order, HttpRequestMessage request)
{
_order = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(_value),
RequestMessage = _request
};
var cookie = new CookieHeaderValue("session-id", "6789");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return Task.FromResult(response);
}
}
You will need to adjust your controller code to call this new class. e.g.
public async Task<IHttpActionResult> Post(Order Order)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
context.Orders.Add(Order);
await context.SaveChangesAsync();
return new OrderResult(Order, request /* not sure how you'll get the request in this scope*/);
}
You can write your own DelegatingHandler to add the cookie you need into the response.
Check the part "Example: Set and Retrieve Cookies in a Message Handler":
http://www.asp.net/web-api/overview/working-with-http/http-cookies
For how to insert a message handler, check this:"Per-Route Message Handlers"
http://www.asp.net/web-api/overview/working-with-http/http-message-handlers
I'm trying to return a status code of 304 not modified for a GET method in a web api controller.
The only way I succeeded was something like this:
public class TryController : ApiController
{
public User GetUser(int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
throw new HttpResponseException(HttpStatusCode.NotModified);
}
return user;
}
}
The problem here is that it's not an exception, It's just not modified so the client cache is OK.
I also want the return type to be a User (as all the web api examples shows with GET) not return HttpResponseMessage or something like this.
I did not know the answer so asked the ASP.NET team here.
So the trick is to change the signature to HttpResponseMessage and use Request.CreateResponse.
[ResponseType(typeof(User))]
public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return new HttpResponseMessage(HttpStatusCode.NotModified);
}
return request.CreateResponse(HttpStatusCode.OK, user);
}
You can also do the following if you want to preserve the action signature as returning User:
public User GetUser(int userId, DateTime lastModifiedAtClient)
If you want to return something other than 200 then you throw an HttpResponseException in your action and pass in the HttpResponseMessage you want to send to the client.
Change the GetXxx API method to return HttpResponseMessage and then return a typed version for the full response and the untyped version for the NotModified response.
public HttpResponseMessage GetComputingDevice(string id)
{
ComputingDevice computingDevice =
_db.Devices.OfType<ComputingDevice>()
.SingleOrDefault(c => c.AssetId == id);
if (computingDevice == null)
{
return this.Request.CreateResponse(HttpStatusCode.NotFound);
}
if (this.Request.ClientHasStaleData(computingDevice.ModifiedDate))
{
return this.Request.CreateResponse<ComputingDevice>(
HttpStatusCode.OK, computingDevice);
}
else
{
return this.Request.CreateResponse(HttpStatusCode.NotModified);
}
}
*The ClientHasStale data is my extension for checking ETag and IfModifiedSince headers.
The MVC framework should still serialize and return your object.
NOTE
I think the generic version is being removed in some future version of the Web API.
In MVC 5, things got easier:
return new StatusCodeResult(HttpStatusCode.NotModified, this);
For ASP.NET Web Api 2, this post from MS suggests to change the method's return type to IHttpActionResult. You can then return a built in IHttpActionResult implementation like Ok, BadRequest, etc (see here) or return your own implementation.
For your code, it could be done like:
public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return StatusCode(HttpStatusCode.NotModified);
}
return Ok(user);
}
I hate bumping old articles but this is the first result for this in google search and I had a heck of a time with this problem (even with the support of you guys). So here goes nothing...
Hopefully my solution will help those that also was confused.
namespace MyApplication.WebAPI.Controllers
{
public class BaseController : ApiController
{
public T SendResponse<T>(T response, HttpStatusCode statusCode = HttpStatusCode.OK)
{
if (statusCode != HttpStatusCode.OK)
{
// leave it up to microsoft to make this way more complicated than it needs to be
// seriously i used to be able to just set the status and leave it at that but nooo... now
// i need to throw an exception
var badResponse =
new HttpResponseMessage(statusCode)
{
Content = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json")
};
throw new HttpResponseException(badResponse);
}
return response;
}
}
}
and then just inherit from the BaseController
[RoutePrefix("api/devicemanagement")]
public class DeviceManagementController : BaseController
{...
and then using it
[HttpGet]
[Route("device/search/{property}/{value}")]
public SearchForDeviceResponse SearchForDevice(string property, string value)
{
//todo: limit search property here?
var response = new SearchForDeviceResponse();
var results = _deviceManagementBusiness.SearchForDevices(property, value);
response.Success = true;
response.Data = results;
var statusCode = results == null || !results.Any() ? HttpStatusCode.NoContent : HttpStatusCode.OK;
return SendResponse(response, statusCode);
}
.net core 2.2 returning 304 status code. This is using an ApiController.
[HttpGet]
public ActionResult<YOUROBJECT> Get()
{
return StatusCode(304);
}
Optionally you can return an object with the response
[HttpGet]
public ActionResult<YOUROBJECT> Get()
{
return StatusCode(304, YOUROBJECT);
}
I don't like having to change my signature to use the HttpCreateResponse type, so I came up with a little bit of an extended solution to hide that.
public class HttpActionResult : IHttpActionResult
{
public HttpActionResult(HttpRequestMessage request) : this(request, HttpStatusCode.OK)
{
}
public HttpActionResult(HttpRequestMessage request, HttpStatusCode code) : this(request, code, null)
{
}
public HttpActionResult(HttpRequestMessage request, HttpStatusCode code, object result)
{
Request = request;
Code = code;
Result = result;
}
public HttpRequestMessage Request { get; }
public HttpStatusCode Code { get; }
public object Result { get; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Request.CreateResponse(Code, Result));
}
}
You can then add a method to your ApiController (or better your base controller) like this:
protected IHttpActionResult CustomResult(HttpStatusCode code, object data)
{
// Request here is the property on the controller.
return new HttpActionResult(Request, code, data);
}
Then you can return it just like any of the built in methods:
[HttpPost]
public IHttpActionResult Post(Model model)
{
return model.Id == 1 ?
Ok() :
CustomResult(HttpStatusCode.NotAcceptable, new {
data = model,
error = "The ID needs to be 1."
});
}
Try this :
return new ContentResult() {
StatusCode = 404,
Content = "Not found"
};
If you need to return an IHttpActionResult and want to return the error code plus a message, use:
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotModified, "Error message here"));
Another option:
return new NotModified();
public class NotModified : IHttpActionResult
{
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.NotModified);
return Task.FromResult(response);
}
}
public HttpResponseMessage Post(Article article)
{
HttpResponseMessage response = Request.CreateResponse<Article>(HttpStatusCode.Created, article);
string uriToTheCreatedItem = Url.Route(null, new { id = article.Id });
response.Headers.Location = new Uri(Request.RequestUri, uriToTheCreatedItem);
return response;
}
An update to #Aliostads answer using the more moden IHttpActionResult introduced in Web API 2.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/action-results#ihttpactionresult
public class TryController : ApiController
{
public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return StatusCode(HttpStatusCode.NotModified);
// If you would like to return a Http Status code with any object instead:
// return Content(HttpStatusCode.InternalServerError, "My Message");
}
return Ok(user);
}
}
I know there are several good answers here but this is what I needed so I figured I'd add this code in case anyone else needs to return whatever status code and response body they wanted in 4.7.x with webAPI.
public class DuplicateResponseResult<TResponse> : IHttpActionResult
{
private TResponse _response;
private HttpStatusCode _statusCode;
private HttpRequestMessage _httpRequestMessage;
public DuplicateResponseResult(HttpRequestMessage httpRequestMessage, TResponse response, HttpStatusCode statusCode)
{
_httpRequestMessage = httpRequestMessage;
_response = response;
_statusCode = statusCode;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(_statusCode);
return Task.FromResult(_httpRequestMessage.CreateResponse(_statusCode, _response));
}
}