In ASP.NET WebAPI, localise the default message for BadRequest - asp.net-web-api

I have ASP.NET WebAPI with culture in web.config and there I have a method, from which I return BadRequest with ModelState parameter. On client side I receive this dictionary, but also a message saying The request is invalid. (in English)
My question is, if there is a way to localise this message or to somehow modify it, when I'm returning ModelState dictionary.
Thanks in advance.

Related

laravel validation during ajax request

Please somebody explain this info from Laravel docs "When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code."
What does "during an AJAX request" exactly mean here?
If I'm set like this:
User submits input from a form in the view.
The route calls the method for post in the controller
The request is validated in the controller
case 1) Request passes validation and input is stored in the DB -> Response is returned as JSON for a script that updates the view on the fly.
case 2) Request doesn't pass validation, what is returned here? I think a redirect and if not how can you check if validation has failed to return a JSON instead?
And is this scenario similar to what the docs talk about? If not then what?
The response to an AJAX call in this case is a JSON string
Case 1: as you said
Case 2: A JSON String with the error messages. Look into your Chrome dev tools into the Network tab, there you'll see the exact responses.
When handling a validation failure, laravel automatically generates an error response. Normally this will redirect the user back to their form, but in the case of an AJAX request it will instead return a JSON response with the details of what failed validation.
Laravel relies on the symfony request object to detect AJAX requests, specifically this line:
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
If you are encountering issues with your requests not being treated as AJAX, make sure your client is properly setting the X-Requested-With header

Changing the Content-Type of error responses in the Django Rest Framework?

I need all error responses in my API to adhere to the Internet Draft "Problem Details for HTTP APIs", which in the context of the Django Rest Framework could simply mean to change the Content-Type of JSON responses to "application/problem+json", while successful responses stick with "application/json". What's the best way to accomplish this?
I considered creating a custom exception handler that would do the following:
If "application/problem+json" is not accepted by the client, a "406 Not Acceptable" response is returned.
Otherwise, call rest_framework.views:exception_handler() and set the response's content type to "application/problem+json". (Assuming that I have a rendered for this type.)
Is there a better way to accomplish this? If not, can you spot any problems with this approach?

NancyFx. Forms authorization. Ajax and unauthorized response

I use wcf-hosted NancyFx with forms authorization with redirection enabled (DisableRedirect = false).
I would like in case of unsuccesfull authorization attempt handle it and signal to user (show some tooltip that user name or password is wrong). How can I do it with FormAuth?
Another approach is to use Ajax post request, but because of redirection I can't get 401 code. If I turn off redirection it works (I can get 401 in ajax post request). But I want to use redirection facilities in my application...
I never work before with FormAuth, so what is my options here?
Thanks in advance!
Well, actually there were obvious solution based on parsing returned querystring (smth like login?error=true&username=a, as in examples for Nancy forms auth app). On document load parse this query string and show tooltip... Another question whether it is standart (good) practise?..

Where do AJAX requests in an MVC application enter the server side code initially?

To keep it simple I have a feedback form on my website. Whether or not the following is best practice is moot as I'm interested in the way this works. The customer can fill out their name, email address and reason for feedback on the form. This is then posted via AJAX to a server side function called SendFeedback. I am using .NET MVC4 and the SendFeedback method simply returns a true or false string. However I was testing out sending scripts through it to check out the security of the form and noticed that when I attempted to send through HTML tags or javascript that the SendFeedback method wasn't being invoked at all and instead my custom error page was being sent back to the client side AJAX response (if I sent though standard text, the SendFeedback method was being invoked as expected). Where is the first place that AJAX data is sent before it is passed into the server side method I am calling from the client? Is there any way to set a breakpoint here so I can examine what is going on?
This is part of an ASP.NET feature called request validaiton which is turned on by default. And which executes in ASP.NET handler before your code. If you desire, this feature can be turned off in web.config, but I would strongly advise against it.
More information on request validation can be found in MSDN.

Is server-side validation an appropriate use of ASP.NET WebAPI ApiController action

Before WebAPI, I did all client-side remote validation calls using regular MVC action methods. With WebAPI, I can now have POST, PUT, DELETE, and GET methods on an ApiController. However, validation still needs to happen.
I have successfully been able to put remote validation action methods on an ApiController and get them to work. Before submitting a POST, PUT, or DELETE for a resource, the client can POST to one or more validation URL's to validate user input and receive appropriate validation messages.
My question is, should these remote validation actions be on an ApiController? Or a regular MVC controller? It seems to me having them all in the ApiController makes the most sense, because that class can then encapsulate everything having to do with resource (and resource collection) mutations.
Update: reply #tugberk
I should elaborate. First, we are not using DataAnnotations validation. There are already rich validation rules and messages configured on the domain layer commands using FluentValidation.NET. Many of the validation classes use dependency injection to call into the database (to validate uniqueness for example). FluentValidation has good pluggability with MVC ModelState, but I have not found a good way to plug it into WebAPI ModelState yet.
Second, we are doing validation at the POST, PUT, and DELETE endpoints. Clients do not need to know the validation endpoints in order to discover what went wrong. Here is an example:
var command = Mapper.Map<CreateCarCommand>(carApiModel);
try
{
_createHandler.Handle(command);
}
catch (ValidationException ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
Clients will get a 400 response along with a message indicating what went wrong. Granted, this is not as granular as the response in the example you linked to. Because we are just returning a string, there is no easy way to parse out which fields each validation message belongs to, which is needed for our own HTML + javascript client of the API. This is why I spiked out adding more granular validation endpoints (as a side note, they are consumed by field-specific knockout-validation calls on our javascript client).
I am assuming that you are referring to something similar to ASP.NET MVC Remote Validation by saying remote validation. In that case, I don't think that your HTTP API needs a remote validation. Think about a scenario where I need to consume your HTTP API with my .NET application and assume that you have a remote validation. Two things bother me here:
That remote validation is not discoverable unless you are providing a .NET client for your API by yourself and put that logic inside that client.
Assuming that the remote validation is there for the .NET client and the application will make a validation call to the server before sending the actual request, this is just a overkill.
In my opinion, the user send a request to your API and you should make the validation there. You can find a sample from the following URL:
ASP.NET Web API and Handling ModelState Validation

Resources