ASP.NET 5, MVC 6, API response status - asp.net-web-api

I have a controller in my MVC 6 API project. There is a post method and what I want is to validate posted value and return some error back to a client if data are not valid.
[HttpPost]
public void Post([FromBody]PostedHistoricalEvent value)
{
if (!IsHistoricalEventValid(value))
{
//return error status code
}
}
Now I wonder why Post method in the default template does not have any returning type but void and how then one should return an error http status code with some message?

An action method that has no return type (void) will return an EmptyResult, or an 200 OK without a response body.
If you want to alter the response, then you can either change the return type and return an HttpStatusCodeResult:
public IActionResult Post(...)
{
// ...
return new HttpStatusCodeResult(400);
}
Or set it on the Controller.Response:
public void Post(...)
{
// ...
Response.StatusCode = 400;
}

Related

Update data with Microsoft.AspNet.WebApi

Hey i am having a big trouble updating data in my client side REST application.
I made a Web API controller.
// PUT: api/Contacts/5
[ResponseType(typeof(void))]
public IHttpActionResult PutContact(Contact contact, int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != contact.ContactId)
{
return BadRequest();
}
_contactService.Update(contact);
return StatusCode(HttpStatusCode.NoContent);
}
And also client side service method:
public async Task<T> PutData<T>(T data, int dataId)
{
HttpResponseMessage resp = await this._client.PutAsJsonAsync(_serviceUrl + "/" + dataId, data);
resp.EnsureSuccessStatusCode();
return await resp.Content.ReadAsAsync<T>();
}
Service URL shows in debug mode that i goes to endpoint:
http://localhost:21855/api/Contacts/8
But it does not even go to breakpoint when i debug my server controller PutContact method.
What i am doint wrong? I need to update the data but i cant, because my client-side application won't even go to servers breakpoint on debug mode!!!
It gives me an error response 405 : Method not allowed
You can't have two different body parameters in the same method.
What you need to do is to set the id parameter to come from the URI and the Contact parameter from the body, like this:
public IHttpActionResult PutContact([FromBody]Contact contact, [FromUri]int id)
{
// method code
}
BTW, I suppose you have a GET method in your controller which looks like this:
public IHttpActionResult GetContact(int id)
{
// method code
return Contact; // pseudo-code
}
The error you getting comes from the fact that the system is not really calling your PUT method but the GET one (the system is ignoring the Contact parameter for the reason I expressed before): calling a GET method with a PUT verb results in a 405 Method Not Allowed exception.

ASP.net 5 Web API Post CreatedAtRoute always returns 500 Internal Server Error

The database works. It does actually insert the new record, but when I use CreatedAtRoute(), I always get a 500 back from the client. Why?
My controller's Get:
[Route("api/[controller]")]
public class IngredientController : Controller
{
private SimpleCookbookDbContext db { get; set; }
public IngredientController(SimpleCookbookDbContext context)
{
db = context;
}
// GET: api/values
[HttpGet]
public async Task<IEnumerable<Ingredient>> Get()
{
return await db.Ingredients.ToListAsync();
}
// GET api/values/5
[HttpGet("{id}", Name = "GetIngredient")]
public async Task<Ingredient> Get(int id)
{
return await db.Ingredients.SingleOrDefaultAsync(i => i.Id == id);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]Ingredient ingredient)
{
try
{
var res = await IM.CreateAsync(ingredient);
if (!res.Success)
{
return HttpBadRequest(res.Errors);
}
}
catch(Exception)
{
return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
}
return CreatedAtRoute("GetIngredient", new { controller="Ingredient", id = ingredient.Id });
}
}
I tried debugging this. Yes, it would return the HttpBadRequest if the ingredient I'm trying to insert already exists.
I tried putting a breakpoint inside the catch block, and I'm not getting there, so I assume there was no error from the database.
The record does get inserted to the database. I do get to the line return CreatedAtRoute(...); but I get a 500 back. (I set a breakpoint there, too).
Now, I'm using fiddler. My request is this:
POST /api/ingredient HTTP/1.1
Host: localhost:55303
Content-Type: application/json;charset=utf-8
{"id":0, "name": "rosemary", "description": "rosemary"}
I also removed the double quotes on the property names, and I still get the same 500.
I do have camel-casing resolved at the Startup:
services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
I think I showed all relevant code. If you need more, please let me know.
UPDATE
CreatedAtRoute has an overload taking in three parameters:
return CreatedAtRoute("GetIngredient", new { controller="Ingredient", id = ingredient.Id }, ingredient);
The last parameter is an object, which you could create dynamically or pass back your entire entity, depending on what you want to expose back.
It's strange how there's a 2-parameter variant that would result in a strange 500 response.

What I am supposed to return from a server-side method called by ajax?

I have the following jQuery script:
$(document).ready(function() {
$("#resendActivationEmailLink").bind("click", function(event) {
$.get($(this).attr("href"), function() {
$("#emailNotActivated").html("<span>not yet activated. email sent!</span>");
}, "html");
event.preventDefault();
});
});
Basically, when a user clicks a link the following server-side method is invoked:
#RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody
String resendActivationEmail(#PathVariable("token") String token) {
preferencesService.resendActivationEmail(token);
return "dummy";
}
and some business logic is executed on the server but there is no real outcome from the server to be used on the client/browser side apart from an ajax success or an ajax failure.
Now what I am really not sure about is what my server-side method is supposed to return!
Currently it just returns the string dummy but of course this is only temporary. Should I go for no return type (void) or null or something else??
Note that I can change the datatype parameter of the jQuery get method.
EDIT:
I have altered my server-side method as follows:
#RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET)
public #ResponseBody void resendActivationEmail(#PathVariable("token") String token) {
preferencesService.resendActivationEmail(token);
}
#ResponseBody is required because this is an ajax call.
There is no point in returning a dummy value in this case. If you are not doing anything with the return value, then you can just do something like this:
#RequestMapping(value="/resendActivationEmail/{token}", method=RequestMethod.GET)
#ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT)
public void resendActivationEmail(#PathVariable String token) {
preferencesService.resendActivationEmail(token);
}
There will be a 204 response code instead of a 200 but that should be fine.
I'm assuming you are returning JSON from the server (from your server code: produces = "application/json").
Since you don't care about what gets returned, i.e. you are not handling the return value in your callback function, after $.get, then you can just return "{}", or if you want to handle the response you can go with something like:
{ "success": true }
// or
{ "error": "Error messages here" }

mvc webapi cross domain post [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
CORS with WebAPI for XmlHttpRequest
I'm trying to implement cross-domain ajax post to my webApi project. I had few troubles with that:
1. I always was getting 204 error until changed my webapi action from
public void submit(Submission model)
to
public bool submit(Submission model)
don't know why, but now I'm getting 200 OK status
2. Still my ajax firing error callback.
3. Long time ago I solved this kind of error of cross-domain posting by adding
HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
to my controller. But now in webApi i'm inherent from : ApiController and this trick doesn't work. Shows me compiler Error an object reference is required for the non-static field, method, or property"System.Web.HttpContext.Response.get"
I have tryed to post via dataType: 'JSONP' but I get null model.
Here goes Javascript request:
var model = {
"type": $("#model-type").val(),
"subject": $("#subject-text").val(),
"body": $("#body-text").val()
};
$.ajax({
type: "POST",
dataType: 'JSONP',
url: $("#submit-url").val(),
data: model,
success: function () {
alert("Succesfully submitted");
},
error: function () {
alert("Error...");
}
});
What I'm doing wrong?
SOLVED
Thanks to everybody for helping me out. I found solution in one of the comment links. I used following approach, which I find pretty simple.
Source:
Implementing CORS support in ASP.NET Web APIs
What I made:
1. Created new Class in my project: CorsHandler.cs and just copy-pasted following code:
public class CorsHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
Opened my Global.asax and modifyed Application_Start :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
}
Pay attention to the last line in action.
This approach is compatible with MVC3 and .NET 4.0. Works great, now I can handle "success" and "error" callbacks in ajax.
Answers to your questions respectively:
Status 204 is not an error, which means no content to return but everything's good. Here's the definition of 204 in RFC2616
10.2.5 204 No Content
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent's active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
Could you articulate what's the error you met? The ASP.NET Web API currently doesn't have a JSONP formatter out of box. Here's some 3rd part implementation:
http://www.west-wind.com/weblog/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API
http://www.nuget.org/packages/WebApi.JsonP
I hope they're helpful.
In Web API the way in which you refers to an Response is not through HttpContext. There are multiple ways to access.
The first option is to define action return HttpResponse directly.
public HttpResponseMessage Get(int id)
{
var response = this.Request.CreateResponse();
response.StatusCode = HttpStatusCode.OK;
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
The second option is to use ActionFilter:
// define action filter for cross domain
public class CrossDomainActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
bool needCrossDomain = true;
if (needCrossDomain)
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
base.OnActionExecuted(actionExecutedContext);
}
}
// At Controller
// GET api/values/5
[CrossDomainActionFilter]
public string Get(int id)
{
return "value";
}
The last option is to use MessageHandler:
public class CrossDomainMessageHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
}
If you want to send information to another domain from ajax then you need to use jsonp (note this only works with get requests not post requests). Another alternative (if you are in control of both domains) is to use ARR (application request routing) to trick the browser into thinking the request is local then using ARR to rewrite the request to another domain. Using this technique you can use simple ajax gets and posts like normal.

Post Scalar data type using HttpClient.PostAsJsonAsync

I am invoking ASP .Net Web API using HttpClient and invoke actions successfully. Also I am able to POST custom object into action as well.
Now problem I am facing is, not able to post scalar data type like Integer,String etc...
Below is my controller and application code that invokes action
// Test application that invoke
[Test]
public void RemoveCategory()
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
HttpResponseMessage response = client.PostAsJsonAsync<string>("http://localhost:49931/api/Supplier/RemoveCategory/", "9").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
// Controller and Action in Web API
public class SupplierController : ApiController
{
NorthwindEntities context = new NorthwindEntities();
[HttpPost]
public HttpResponseMessage RemoveCategory(string CategoryID)
{
try
{
int CatId= Convert.ToInt32(CategoryID);
var category = context.Categories.Where(c => c.CategoryID == CatId).FirstOrDefault();
if (category != null)
{
context.Categories.DeleteObject(category);
context.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Delete successfully CategoryID = " + CategoryID);
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Invalid CategoryID");
}
}
catch (Exception _Exception)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, _Exception.Message);
}
}
When I Post custome object that represent "Category" table in Northwind database all things working properly but I am not able to post scalar data like Integer and String
When I am post string data type I am getting following exception
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:49931/api/Supplier/RemoveCategory/'.","MessageDetail":"No action was found on the controller 'Supplier' that matches the request."}
Can anyone guide me?
You will have to mark your CategoryID parameter as [FromBody]:
[HttpPost]
public HttpResponseMessage RemoveCategory([FromBody] string CategoryID)
{ ... }
By default, simple types such as string will be model bound from the URI.

Resources