WebApi - Specify Content-Type in Uri - asp.net-web-api

You can use
AddUriPathExtensionMapping("json", "application/json");
To enable media type to be specified as part of the uri as seen below
http://localhost/products.json
How can I get WebApi to allow me to post to this uri without having to specify a Content-Type header. I would like WebApi to use the extension to determine the Content-Type.

Question: Why would you want to specify the Content-Type in the Uri? Usually specifying the media type in the Uri is for GET kind of scenarios and where the user does not have a way to provide the Accept header. For example, in the browser address bar, one could enter /products.json or /products.xml to see the results.
For all other scenarios where you can make a request with headers, you should be sending them in regular way. Could you describe your scenario more?
Edited:
If you indeed are looking for GET requests, then you could do like in the following example:
Register routes like below:
config.Routes.MapHttpRoute(
name: "DefaultApiWithExtension2",
routeTemplate: "api/{controller}/{id}.{ext}"
);
config.Routes.MapHttpRoute(
name: "DefaultApiWithExtension1",
routeTemplate: "api/{controller}.{ext}");
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "application/xml");
config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
If your application is hosted in IIS, then you would see errors in using the . character in the url. You can resolve this by having the following setting in Web.Config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />

You could add a server side message handler that parses the URI and sets the Content-Type header before it reaches the ApiController.

Related

How to set default swagger welcome page in Web Api

I have created a Web Api, and I want to set default landing url as Swagger url i.e:-
http://localhost:65347/swagger/ui/index
Maybe not the most accurate answer, but I simply set the Startup URL in my project to the Swagger page. You'll have to make sure the path is correct when you deploy, but works great for me when debugging on my workstation.....
I have resolved this by adding below code in RouteConfig.cs
routes.MapHttpRoute(
name: "swagger",
routeTemplate: "",
defaults: null,
constraints: null,
handler: new RedirectHandler((url => url.RequestUri.ToString()), "swagger"));

How to configure OPTIONS request in CORS to Access-Control-Allow-Origin with ASP.NET Web API

I'm having an issue trying to get a token from my server on an Angular 5 project. My POST request is never sent and the server returns 400 Bad Request and shows the following in the console:
My understanding is that I need to configure the OPTIONS request in CORS to allow the cross-origin request, but I feel like I've tried every solution there is out there without any success.
As far as what I have tried so far, in my Web.config I have this:
And I enabled CORS globally in my WebApiConfig.cs:
I even implemented the solution suggested at https://www.stevefenton.co.uk/2012/11/using-cors-with-asp-net-web-api/
Here is the call I am making in my Angular 5 project:
userAuthentication(userDetails: LoginUser): Observable<LoginUser> {
var data = "username=" + userDetails.username + "&password=" + userDetails.password + "&grant_type=password";
var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'No-Auth': 'True' });
return this.http.post<LoginUser>(this._baseUrl + 'Token', data, { headers: reqHeader })
.pipe(
catchError(this.handleError)
)
}
When I make the call using POSTMAN, everything runs smoothly and I get my access_token.
I've managed to resolve this issue. I needed to add Microsoft.Owin.Cors with Microsoft.AspNet.Cors and Microsoft.AspNet.WebApi.Cors.
I then had to add app.UseCors(CorsOptions.AllowAll); to my Startup.cs file:
…and remove the customHeaders from between the system.webserver tags in Web.config:
All is running smoothly now.
Note: It's important to note that when enabling CORS on your WebApiConfig.cs, if you have followed the previous steps I have shown, you must enable it like this:
…and not like this:
If you do, you will get an error stating your header contains multiple values and therefore will deny your Origin access.

Web API routing 404 not found

I'm getting a 404 not found error when trying to access one of my Web API actions:
I have in my WebAPIConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I have a controller named OnSourceAPIController and a GET action ValidateServiceRequestAuto.
I get a 404 error when I try to go to:
http://localhost/api/OnSourceAPI/ValidateServiceRequestAuto
My first guess was I had some kind of routing error, but I created an mvc controller and an index page for it and was able to browse there normally via this routing (api/controller/action). The builtin api/help page even shows /api/OnSourceAPI/ValidateServiceRequestAuto as the route to my api call.
I also tried using the WebAPIRouteDebugger tool. It gives me a 000 404 not found error when I use
http://localhost/api/OnSourceAPI/ValidateServiceRequestAuto
, but actually give me the normal route information if I take localhost off of the front and just use
api/OnSourceAPI/ValidateServiceRequestAuto as the URL...
Any pointers would be appreciated.
I figured it out and feel a little bit silly now.
I have my webapi project running inside of my normal website project with a path of .../api, so because I set up my api routing to be api/controller/action, the path I really need to use is localhost/api/api/controller/action. So it turns out that the 404 was there because it really couldn't find anything at that location. I hate it when computers do exactly what you tell them to.
In my case it was address of created service: WebApp.Start(address)
Should be like: http://localhost:9000/
NOT: http://localhost:9000/api/

Exception while passing JSON string(multiple parameters) to method in WebAPI service

While trying to pass a JSON data from script side to the method inside WebAPI service we are getting the following exception.
{
"Message":"No HTTP resource was found that matches the request URI '.../api/Values/Sample'.",
"MessageDetail":"No type was found that matches the controller named 'Values'."
}
IMPORTANT NOTE:
While using WebAPI in .net 4.0 and VS2010 we didn’t experience any such issue but when we use WebAPI in .net 4.5 and VS2012 we saw the issue. So kindly diagnosis this with 4.5 framework.
We have attached the sample in the following link. If you could review and post the correct sample with comments it would be really helpful as we are new to WebAPI concepts. Event posting code snippet with proper comments would be fine.
SAMPLE LINK: http://www.fileconvoy.com/dfl.php?id=gb197faeca5017d489993001280c7f122f64fc06a7
Thanks in advance.
I have looked at your sample. Couple of things to fix it:
1.Change the controller name from ValuesController1 to ValuesController. Web API by default looks for controller classes with suffix 'Controller'.
2.Change your route to the following:
System.Web.Routing.RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional});

ASP.NET MVC 3 Access Denied in just one server and one folder

I'm with the following issue: when I try to access a certain page (http://mysite.com/Client/) I get an Access Denied error (403 - Forbidden: Access is denied), but if I try to access the same URL using "Index" in the end (http://mysite.com/Client/Index), it works! And I have a lot of another folders that work without the "Index" in the URL.
The wierdest part is that in the test server (http://mysite.com:8080) I can access in both ways (/Client/ and /Client/Index/). By this time I don't know if it's an IIS 7 problem, or in the Client Folder for some reason, if it's in Web.config or if I'm just losing my mind!
The routes are the following:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
);
One more thing: the test server app and the main server app are the same!
Can someone give me a hand? Thank you!
P.S.: There isn't any authorization setting in web.config.
From your question it seems like you don't have a Client controller, just folder. So, I guess the route is looking for a controller that It can't find. Or you have a controller but no actions in it. I am not sure, anyway, try adding this to your routes:
routes.IgnoreRoute("Client/{*path]");
EDIT:
Try adding this route:
routes.MapRoute(
"Default", // Route name
"{controller}/Index", // URL with parameters
new { controller = "Home", action = "Index"}
);
resolved in a mysterious way: although I tried to resolve things editing the routes, I realized that the error was occurring before the application_start event. So, the problem was in IIS.
I tried to find the reason for the problem, but I couldn't, so I installed the URL Rewrite 2.0 and made the request of "/Client" redirect to "/Client/Index".
Wierd, isn't it? But this workaround resolved!
Thaks for all the answers!

Resources