Handling bad request in asp.net web api - asp.net

I have a api url like below in my mvc4 app
http://localhost:15839/api/mydata/getdata/3365895543/PROBLEMDATA/myotherparam
Now client is consuming the above url to send httprequest. In response api is sending back a response. but in PROBLEMDATA of the url user is sending bad characters that are giving me Bad Request - Invalid URL. I can't force my client source to encode data. i need to handle it in my web api and give back my client a string "Unsucessful". I have seen this webapi cycle wondering at which point I should handle this. probably at http message handler but How?
I may need to follow this. but Register(HttpConfiguration config) also doesn't get hit

I believe you can capture this globally by overriding the application_error method. From there I suppose you could produce the "unsucessful" response or pass the request along to be handled at the controller level.
Take a look at this question as well.

Related

How to post to an internal URL in classic asp from server

How to post to an internal URL in classic asp from server?
Using MSXML2.ServerXMLHTTP looks not work per this and this
I cannot use Response.Redirect since I need to send http code 200 right after I receive the request
I cannot use either Server.Execute or Server.Transfer since I want to modify Form collection before posting to destination internal URL
Thank you
Update:
I create an classic ASP endpoint to accept request from a third party. And I need to send back a response with HTTP status code 200. Then this endpoint doesn't process anything but needs to post the request to an internal endpoint for processing. Hope this clear now.
Khoi

URL not changed using servlet [duplicate]

What is the conceptual difference between forward() and sendRedirect()?
In the web development world, the term "redirect" is the act of sending the client an empty HTTP response with just a Location header containing the new URL to which the client has to send a brand new GET request. So basically:
Client sends a HTTP request to some.jsp.
Server sends a HTTP response back with Location: other.jsp header
Client sends a HTTP request to other.jsp (this get reflected in browser address bar!)
Server sends a HTTP response back with content of other.jsp.
You can track it with the web browser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.
Exactly the above is achieved by sendRedirect("other.jsp"). The RequestDispatcher#forward() doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.
Client sends a HTTP request to some.jsp.
Server sends a HTTP response back with content of other.jsp.
However, as the original HTTP request was to some.jsp, the URL in browser address bar remains unchanged. Also, any request attributes set in the controller behind some.jsp will be available in other.jsp. This does not happen during a redirect because you're basically forcing the client to create a new HTTP request on other.jsp, hereby throwing away the original request on some.jsp including all of its attribtues.
The RequestDispatcher is extremely useful in the MVC paradigm and/or when you want to hide JSP's from direct access. You can put JSP's in the /WEB-INF folder and use a Servlet which controls, preprocesses and postprocesses the requests. The JSPs in the /WEB-INF folder are not directly accessible by URL, but the Servlet can access them using RequestDispatcher#forward().
You can for example have a JSP file in /WEB-INF/login.jsp and a LoginServlet which is mapped on an url-pattern of /login. When you invoke http://example.com/context/login, then the servlet's doGet() will be invoked. You can do any preprocessing stuff in there and finally forward the request like:
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
When you submit a form, you normally want to use POST:
<form action="login" method="post">
This way the servlet's doPost() will be invoked and you can do any postprocessing stuff in there (e.g. validation, business logic, login the user, etc).
If there are any errors, then you normally want to forward the request back to the same page and display the errors there next to the input fields and so on. You can use the RequestDispatcher for this.
If a POST is successful, you normally want to redirect the request, so that the request won't be resubmitted when the user refreshes the request (e.g. pressing F5 or navigating back in history).
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
request.setAttribute("error", "Unknown login, please try again."); // Set error.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}
A redirect thus instructs the client to fire a new GET request on the given URL. Refreshing the request would then only refresh the redirected request and not the initial request. This will avoid "double submits" and confusion and bad user experiences. This is also called the POST-Redirect-GET pattern.
See also:
How do servlets work? Instantiation, sessions, shared variables and multithreading
doGet and doPost in Servlets
How perform validation and display error message in same form in JSP?
HttpServletResponse sendRedirect permanent
requestDispatcher - forward() method
When we use the forward method, the request is transferred to another resource within the same server for further processing.
In the case of forward, the web container handles all processing internally and the client or browser is not involved.
When forward is called on the requestDispatcherobject, we pass the request and response objects, so our old request object is present on the new resource which is going to process our request.
Visually, we are not able to see the forwarded address, it is transparent.
Using the forward() method is faster than sendRedirect.
When we redirect using forward, and we want to use the same data in a new resource, we can use request.setAttribute() as we have a request object available.
SendRedirect
In case of sendRedirect, the request is transferred to another resource, to a different domain, or to a
different server for further processing.
When you use sendRedirect, the container transfers the request to the client or browser, so the URL given inside the sendRedirect method is visible as a new request to the client.
In case of sendRedirect call, the old request and response objects are lost because it’s treated as new request by the browser.
In the address bar, we are able to see the new redirected address. It’s not transparent.
sendRedirect is slower because one extra round trip is required, because a completely new request is created and the old request object is lost. Two browser request are required.
But in sendRedirect, if we want to use the same data for a new resource we have to store the data in session or pass along with the URL.
Which one is good?
Its depends upon the scenario for which method is more useful.
If you want control is transfer to new server or context, and it is treated as completely new task, then we go for sendRedirect.
Generally, a forward should be used if the operation can be safely repeated upon a browser reload of the web page and will not affect the result.
Source
The RequestDispatcher interface allows you to do a server side forward/include whereas sendRedirect() does a client side redirect. In a client side redirect, the server will send back an HTTP status code of 302 (temporary redirect) which causes the web browser to issue a brand new HTTP GET request for the content at the redirected location. In contrast, when using the RequestDispatcher interface, the include/forward to the new resource is handled entirely on the server side.
The main important difference between the forward() and sendRedirect() method is that in case of forward(), redirect happens
at server end and not visible to client, but in case of
sendRedirect(), redirection happens at client end and it's visible to
client.
Either of these methods may be "better", i.e. more suitable, depending on what you want to do.
A server-side redirect is faster insofar as you get the data from a different page without making a round trip to the browser. But the URL seen in the browser is still the original address, so you're creating a little inconsistency there.
A client-side redirect is more versatile insofar as it can send you to a completely different server, or change the protocol (e.g. from HTTP to HTTPS), or both. And the browser is aware of the new URL. But it takes an extra back-and-forth between server and client.
SendRedirect() will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.
RquestDispatcher is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect() method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.
Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.
For example in the payment application
we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.
For other scenarios, forward is efficient to use since as it is faster than sendRedirect
Request Dispatcher is an Interface which is used to dispatch the request or response from web resource to the another web resource. It contains mainly two methods.
request.forward(req,res): This method is used forward the request from one web resource to another resource. i.e from one servlet to another servlet or from one web application to another web appliacation.
response.include(req,res): This method is used include the response of one servlet to another servlet
NOTE: BY using Request Dispatcher we can forward or include the request or responses with in the same server.
request.sendRedirect(): BY using this we can forward or include the request or responses across the different servers. In this the client gets a intimation while redirecting the page but in the above process the client will not get intimation
Simply difference between Forward(ServletRequest request, ServletResponse response) and sendRedirect(String url) is
forward():
The forward() method is executed in the server side.
The request is transfer to other resource within same server.
It does not depend on the client’s request protocol since the forward () method is provided by the servlet container.
The request is shared by the target resource.
Only one call is consumed in this method.
It can be used within server.
We cannot see forwarded message, it is transparent.
The forward() method is faster than sendRedirect() method.
It is declared in RequestDispatcher interface.
sendRedirect():
The sendRedirect() method is executed in the client side.
The request is transfer to other resource to different server.
The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
New request is created for the destination resource.
Two request and response calls are consumed.
It can be used within and outside the server.
We can see redirected address, it is not transparent.
The sendRedirect() method is slower because when new request is created old request object is lost.
It is declared in HttpServletResponse.

Can't get authentication token from web api 2

I am new to Web Api 2. I am trying to build a project to explore token authorization. I created a new project in VS 2013 and selected the WebApi2 template and used Fiddler to emulate http requests. I didn't change anything in the template, just ran it as it was and tried to play with it with Fiddler. I successfully created a user by issuing request to /api/account/register but I can't login by issuing a POST request to the /Token endpoint. The request is:
http://localhost:YYYY/token?grant_type=password&password=admin123456&username=admin
(i also tried to pass the parameters as a json object in the request body).
I get back this:
{"error":"unsupported_grant_type"}
From other posts such as ASP.NET WEB API 2 OWIN Authentication unsuported grant_Type I learned that I needed to enable CORS for web api and at the token endpoint, but that hasn't worked for me.
Are you sure that you are sending POST request message and not GET?
If you simply go to the URL with query string (or open connection to this URL from your code) you are sending GET message by default. It's not what WebAPI with "/token" path is listening for.
If you are calling web service from same place, CORS is not needed. The error "unsupported_grant_type" could be in the format of the data you are passing server in post action.
Try sending with Content-Type application/x-www-form-urlencoded

(REST ) Client - set the javax.servlet.http.HttpServletRequest into request How to?

A lot of web applications must be used the specified REST service. This REST service uses currently the informations only from javax.servlet.http.HttpServletRequest. This HttpServletRequest may be contain the specific cookie and other parameters.
I'm try to use the (REST) client API form JERSEY to realize a client, that will build the REST requests. This client will be called within custom web filter, that will be registered by web.xml of each web application.
Currently i have the following problem: i'm don't know, howto transmitt the HttpServletRequest during call of the REST Service....
Thx for your help....
So if I understand correctly, you want receive a request in any of the web applications, and then you want to forward this request to the REST web service?
If so, you will need to serialize the request to make it transportable. You could also create a class that is able to hold the data that you need from the javax.servlet.http.HttpServletRequest and then serialize it into XML or JSON.
If you have the request in a more transportable format, you can pass it to your REST service via a #HeaderParam or as the request body (I would prefer the latter).

Generating HTTP Request

In how many ways can an HTTP request be generated?
There are endless ways how you can create and from where you can send HTTP requests to a server. Actually your server has no idea, what the origin of such a request is (if it's AJAX or "regular" request, or sent from a console application or ...)
But there are HTTP methods (HTTP verbs) that (can) tell the server about the intent of the request: http://en.wikipedia.org/wiki/HTTP_Verbs#Request_methods
Also you can set headers in a request, for example the content-type or the accepted encoding: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Most JavaScript libraries for example set the (non-standard) HTTP header X-Requested-With, so your application can differentiate between regular and ajax requests.
You see, it's even possible to set your own, non-standard headers. There are endless possible combinations...
HttpRequest is a C# class that wraps a petition sent by a client during a Web request.
There are many ways to generate it. The most usual one happens when your browser connects to an ASP.NET website.
You can, for example, create your own custom HttpRequest to petition a specific web page from a C# console application.
Are you trying to achieve something more specific?

Resources