Redirect to error controller in web Api - asp.net-mvc

I write project WEB API 2 and I'd like to show json result in my custom format when I user wrong url like "localhost/api/v1/" or "localhost/api", for this I tryed to create ErrorController with get request which will return message about error. I add route config to WebApiConfig:
config.Routes.MapHttpRoute(
"ErrorInApi",
"v{version}",
new {controller ="Error" }
);
How I can write config to redirect in error controller in all wrong url cases?

Most of the times you use exception filters to deal with exceptions in web api, however you can use them to deal with exceptions during routing, which is the case OP asks. So you may use two new things web api offers you: IExceptionLogger and IExceptionHandler which receive instance of ExceptionContext. Linked page provide sample implementation of such hander and logger.

Related

Send POST request in ATG with checkFormRedirect method

I have requirement of changing GET to POST redirection to external URL.
Currently, we are using checkFormRedirect(url,req,res) to redirect to external URL which by default uses GET as per my understanding. I want to change this request to POST.
One way is we can use HTTPClient API for re-direction.
Is there any way ATG out of box provide some thing to POST redirection. Please help.
If you submitted a form in JSP as you are using checkFormRedirect(). It is already a POST request and you can get data in your handlerXXX method.
You can use this method to control redirects. The API call of this method looks somewhat like:-
public boolean checkFormRedirect(pSuccessURL, pFailureURL, pRequest, pResponse);
Now, this method redirects to pSuccessURL if no form errors are found in the form. Otherwise, it redirects to pFailureURL.

URLs with several path components get sent directly to static file handler

I have the following problem with an Asp.net MVC application when running on IIS (tested with version 7.0 and 8.5) : if the path in the URL has no more than 3 components (for example http://myhost.com/a/b/c, it gets correctly handled by the application code. But when an additional component is added in the path (http://myhost.com/a/b/c/d), it will be sent directly to the static file handler. As the path is not used for a physical file, I get a 404 (with the error page coming from the static file handler, not the custon 404 page configured in web.config)
I don't have this problem on my dev station running IIS Express.
I use runAllManagedModulesForAllRequests="true" in web.config, disabling it doesn't solve the issue.
Disabling the static file handler doesn't help, I still get a 404 but this time the error message says "Handler Not yet determined".
I really looks this is something happening very early in IIS processing, because if I recycle the application pool and try to access to this URL, the response comes immediately, without the usual delay that I get when the application needs to start.
What am I missing? Why is IIS not forwarding such requests to my application?
It's your routes!!
The default route in MVC only takes over controller, action & ID. You're trying to use a fourth which you haven't defined. Just add another url parameter to your route collection.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{another}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, another= UrlParameter.Optional }
);
Hope this helps.
I think I found something: the long url was not handled by an MVC route, but by an OWIN middleware. Somehow, it seems that for IIS, if no route is configured for an URL, then the request pipeline is completely ignored, including any OWIN middlewares (and also custom page for 404).
By adding another parameter in a route like suggested by heymega, I was able to work around the problem, the OWIN middlewares were executed. I added the following route:
routes.MapRoute("CatchLongUrls", "{a}/{b}/{c}/{*d}",
new {controller = "Invalid", action = "Nothing"});

ASP.NET WEB API 406 error:for POST request using Media format

I am very new to web api stuff:
I am getting an error
406: Not Acceptable
error message in asp.net web api rest service.
In my rest service I’m using media format for my customized XML output, to get customized output.
I’m registering my formatted media in Global.asax page.
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new mynewformat());
all my methods are post methods with typed object as parameter and parameters are accepts from body.
Whenever I try to test the service… Getting 406: Not acceptable error message.
can anyone please help me ... what could be the reason for this....???
I did notice couple of interesting points here...
If I’m commenting below line then I’m getting 200 (OK) status code (which is fine.)... but format is not applying to output.
GlobalConfiguration.Configuration.Formatters.Clear();
If i'm removing parameters in my service method.. Then its working
fine..
I request everyone.. Please guide me what could be the reason/work around/solution/fix..for this issue.
Note:I don't want accept parameters from URI so i made it to accept from frombody only.
Thanks.
There is a lot more to implementing a custom format than just adding it to the configuration formatters. It starts with having to change the media-type header to a new custom type of your choosing (like "application/myNewFormat") for all requests, for the client. On the back end, you have to implement a new MediaTypeFormatter that can handle the serialization. This involves a bit more of code.
A good example of this resides here, it can easily be stripped to boiler-plate code:
http://www.codeproject.com/Articles/559378/Implementing-Custom-Media-Formatters-in-ASP-NET-We

301 redirect in ASP.NET MVC from known URL's

I have a .Net MVC 1 site that replaced a legacy. Google still has a stack of old URL's in its index and i need to 301 redirect them. All of the old URL's are .html or .php pages, i also have a db table for old urls and their new equivalent. I know what i need to do, im just unsure of how to do it! Here are my thoughts
somewhere in the global.asax catch the url requested using a regexp
do a db lookup to hopefully find the new url
if we found the new url then 301 redirect it. if not either 301 to the homepage or throw a 404
Ive tried hacking around myself with little luck, plus all of the examples i can find online dont really cover this example. Would really like to do this via code rather than adding about 80 seperate routes to the global.asax
Any help or links is greatly appreciated
You could probably use Handlers. If the URLs are distinct enough, you could write a pretty broad entry in to urlMappings section of your web.config and then use the handler to re-route the traffic.
I'd use the catch all route and before returning that 404 I'd insert the logic to check if it needs a 301 instead.
[UrlRoute(Name = "404", Path = "{*path}", Order = 100)]
public ViewResult NotFound(string path)
{
}

Verify that a URL maps to an actual route in ASP.Net MVC

To support legacy URLs in my application, I use a regex to convert URLs of the form /Repo/{ixRepo}/{sSlug}/{sAction} to the new form /Repo/{sName}/{sAction}, using the ixRepo to get the correct sName. This works well, and I can redirect the user to the new URL with a RedirectResult.
However, I'd like to catch legacy URLs with an invalid action before I redirect the user. How can I verify if a URL string will map to a registered route? MVC clearly does this internally to map a request to the correct action, but I'd like to do it by hand.
So far, I've come up with this:
var rd = Url.RouteCollection.GetRouteData(new HttpContextWrapper(new HttpContext(
new HttpRequest("", newPath, ""),
new HttpResponse(null))));
which appears to always return a System.Web.Routing.RouteData, even for bad routes. I can't find a way to check if the route was accepted as a catch all, or if actually mapping to a route that's registered on the controller.
How can I use MVC's routing system to check if a URL maps to a valid controller/action via a registered route?
(I've seen ASP.NET MVC - Verify the Existence of a Route, but that's really inelegant. MVC has a routing system built in, and I'd like to use that.)
Wrong question. Anything can be a route, whether or not it actually maps to an action.
I think you're asking, "Will this execute OK, or will it 404?" That's a different question.
For that, you need to do what MVC does. Look in the MVC source at MvcHandler.ProcessRequestInit and then ControllerActionInvoker.InvokeAction to see how MVC looks up the controller and action, respectively.
If you know the controller and ask for valid actions, just do some reflection stuff as done in here.
If the redirected url goes to your application, then you can check if the url goes to a valid route. Some code on haacked.com http://haacked.com/archive/2007/12/17/testing-routes-in-asp.net-mvc.aspx does route testing as a unit test. After this you have controller and action as routedata and you have to do, what Craig said "do the same as mvc does".
The routing system maps request uris to route handler. The mvc route handler (class) throws an exception if it fails. There is no checking.
You can add constraints to your routes. If you constrain the action property. Then checking if the url goes to a valid route my be what you want.

Resources