I am writing the service for Authenticate user using webapi service in asp.net mvc4,
This service is used in mobile app when the user login the using mobile app the Authenticate should
be happen and I had written code for encrypted and decrypted here followed article
http://www.codeproject.com/Articles/630986/Cross-Platform-Authentication-With-ASP-NET-Web-API
error:
HTTPS is required for security reason.
Below error is displaying.
When check in browser or fiddler it's displaying the same error.
public static void Register(HttpConfiguration config)
{
TokenInspector tokenInspector = new TokenInspector() { InnerHandler = new
HttpControllerDispatcher(config) };
config.Routes.MapHttpRoute(
name: "Authentication",
routeTemplate: "api/User/{id}",
defaults: new { controller = "User" }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: tokenInspector
);
config.MessageHandlers.Add(new HTTPSGuard());
}
As it happens, I'm currently working on a project inspired by the same CodeProject article that you mentioned, so I'm intimately familiar with how it works.
The error you're getting simply means that you need to use HTTPS (not HTTP) to access your api. So, something like: https://localhost:port/api/values. In order to do that, simply using https as your URI scheme is not enough. You need to generate a self-signed certificate (or use a real one if one is available for you) and then attach it to your host -- IIS or self-hosting have different steps to achieve this. There are various websites that can help you complete these steps; this question seems to have a very comprehensive explanation.
If you don't care about HTTPS, then remove the HTTPSGuard message handler from your code and the last line in your Register function where it's being added to the MessageHandlers pipeline.
Related
I have a .NET project that has a Web API portion to it which should be accepting requests externally. The action accepts an object which is then used further on. The problem is when testing with postman app, the action is hit but variables are not passed.
Here is an example of my URL in postman: http://localhost:12345/api/login/postlogin?Username=un&Password=pw
I have tried using [frombody], this would work only if I am receiving a single string. My application will be utilizing lots of data passing back and forth. I have also tried multiple solutions on StackOverflow including [FromUri]. The post is still null.
WebAPi.Config snippet:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Action within Controller:
// POST: api/postLogin/
[AllowAnonymous]
[System.Web.Http.HttpPost, System.Web.Http.Route("postlogin")]
public async Task<IHttpActionResult> PostLogin(LoginDTO login)
{
}
The expected result as stated early is to receive variables as an object then use them within the action.
Your configuration for Routing is correct. You should use [FromBody] attribute to the parameter, because this is a POST request.
you should never use GET request to do authentication!
public async Task<IHttpActionResult> PostLogin([FromBody]LoginDTO login)
I am developing a MVC web application. Testing locally
http://localhost:28847/Place/Malaysia works perfectly how ever, When I deploy this web application in hosting server
http://videeows.com/Place/Malaysia I get 404 - File or directory not found.
The app is deployed in asp.net version 4.5 in the server.
What could have possibly gone wrong?
There are other MVC sites deployed in the machine which works perfectly.
my MVC is just a redirection.
http://videeows.com/Place/Malaysia this will redirect to http://videeows.com/Place.aspx?s=Malaysia&q=Coun
http://videeows.com will direct to http://videeows.com/default.aspx
my routeconfig is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Place",
url: "Place/",
defaults: new { controller = "Place", action = "Index" }
);
routes.MapRoute(
name: "PlaceByCountry",
url: "Place/{country}",
defaults: new { controller = "Country", action = "IndexByCountry", country = "" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional });
}
This is unlikely to be a problem with ASP .NET MVC code. It must be to do with the way you have set-up the server. It's difficult to say what it is though. Make sure that your app pool supports the .NET version which you are using etc.
Check your IIS Server settings and App pool you are using. Just fire and check http://localhost:8080/ IIS working
Make sure that your app pool supports the .NET version which you are using.
I've had the same problem : for certain pages, I get a 404 Error message. In fact is that the server does not consider the last part of the URL as an "id", but instead a folder name. And indeed this folder doesn't exist. I think it can happens when a link is just a call to RedirectToAction to another function...
A solution can be, Instead of using :
AreaName/ControllerName/FunctionName/IdReference
use
AreaName/ControllerName/FunctionName?Id=IdReference
I have built a Asp.Net MVC application, and it's worked successfully.
However, when I published it to IIS I can't access the web service.
I mean, when I enter some url of content (for example "http://localhost/MyApp/Contents/SomePage.html") it's works successfully,
but when I enter url of the api ("http://localhost/MyApp/api/SomeController/SomeMethode") I get 404.2 error.
[When I Entered such url when it was unpublish,("http://localhost:5092/api/SomeController/SomeMethode") it's showed me the result of the method]
Thanks a lot, and sorry for the bad english.
UPDATE
Thanks for the answers, I tried both of them (in the comment and in the answer) and It's didn't work. Actually, I tried to solve it 4 hours and I just couldn't. So like every angry guy I removed the publish and published it again (Just like restarting the computer when it's stuck) and I don't know why, but now it's works.
Thanks again, and sorry again for the bad English.
MVC routing is different from WebApi routing.
MVC:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
WebApi
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
In your Global.asax
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
I've been googling for about an hour and not found an example so I thought I'd ask here.
I am replacing a standard mvc controller with a webapi and having problems with the routing, I've changed the names because of the organisation but they are still valid.
my webapi is currently called SystemAPI in the controllers folder - I want it to have a different name that the url that points to it ideally.
The url I need to point to it is /v1Controller/{id}
I cant change the v1Controller url as it is a fixed point with apps I have no control over
my current coding attempt is
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DocumobiApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "V1Controller",
routeTemplate: "v1Controller/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
to which I get the response
"message":"No HTTP resource was found that matches the request URI 'http://localhost:38685/v1Controller'.","messageDetail":"No route providing a controller name was found to match request URI 'http://localhost:38685/v1Controller'"}
I'm sure its something fairly obvious but cant for the life of me figure it out.
Cheers,
Steven
As the following error message says, a route match should result in providing value for the controller route variable which Web API depends on for selecting a controller.
No route providing a controller name was found to match request URI 'http://localhost:38685/v1Controller
So you could modify the route like below(notice the default value for controller variable):
config.Routes.MapHttpRoute(
name: "V1Controller",
routeTemplate: "v1Controller/{id}",
defaults: new { id = RouteParameter.Optional, controller="SomeControllerHere" }
);
Make sure your action method on your controller has an id with a default value.
I have been trying for a few days to solve this problem so I may in fact be trying to solve the wrong problem or don't know the right terms to search so here goes.
I'm creating a SPA with AngularJS and Web Api (4.5). All of my views are client side. So the server doesn't know all the possible routes that may become present in the URI. This isn't a problem until a user uses one of the browser controls (back, forward, refresh, history) and the server attempts to route the requested URI.
My thoughts on dealing with this have centered around mapping all non API routes to the root of the application.
So I would like to either, know the correct syntax for MapHttpRoute to pick up any route that does not attempt to reference controllers (API's) or if there is a better method for dealing with this problem.
public static void Register( HttpConfiguration config )
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//
// This doesn't work
//
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{*catchall}"
);
}
This XML file does not appear to have any style information associated with it. The document tree is shown below.
No HTTP resource was found that matches the request URI 'http://localhost:9234/login'.
No route providing a controller name was found to match request URI 'http://localhost:9234/login'
Not a good idea, just workaround
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{*catchall}",
defaults: new { controller = "Spa"}
);
[AllowAnonymous]
public sealed class SpaController : ApiController
{
public HttpResponseMessage Get()
{
var indexHtml = HostingEnvironment.MapPath("~/index.html");
var stringContent = new StreamContent(File.OpenRead(indexHtml));
var response = new HttpResponseMessage(HttpStatusCode.OK) {Content = stringContent};
return response;
}
}