handle static file-paths with specified controller in ASP.NET MVC3 - asp.net-mvc-3

i have this map-route in my global:
routes.MapRoute(
"SiteMap",
"sitemap.xml",
new { controller = "Feed", action = "SiteMap" }
);
in local, it works, but on the server doesn't! how can I force the server to pass this url-requests to my application? my server is IIS 7.5 and i can remote to iis.

I found my answer myself! thanks to all;
in web.config:
<system.web>
<urlMappings enabled="true">
<add url="~/sitemap.xml" mappedUrl="~/Feed/SiteMap"/>
</urlMappings>
</system.web>

Related

Error facing on communication between asp.net webapi server and angular2 application

I am facing the CORS related issue when i try to connect my angular2 application and asp.net webapi application.
Error:-
register:1 Access to XMLHttpRequest at 'http://localhost:49457/api/UserDetails' from origin 'http://localhost:4200' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:4200, http://localhost:4200', but only one is allowed.
Here is my code for connecting for calling asp.net webapi url through my angular2 app:-
User.service.ts
GetUser(userobj:user):Observable<User>
{
return this.http.get<User>(`http://localhost:49457/api/UserDetails`,{responseType:"text"})
.subscribe(
function(response)
{
console.log("user details retreived successfully");
},
function(error)
{
console.log(error);
});
}
This is my code for asp.net webapi,
public class UserDetailsController : ApiController
{
private sampledbEntities dbentity = new sampledbEntities();
// GET api/<controller>
public IQueryable<Userdetail> GetUserdetails()
{
return dbentity.userdetails;
}
}
Actually when i run my asp.netwebapi server it is retrieving data correctly through browser.And also i have enabled
CORS in webapiconfig.cs,
void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(corsAttr);
}
in web.config.cs,
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
<add name="Access-Control-Allow-Headers" value="Origin, Content-Type, X-Auth-Token" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
After enabling CORS in Webapiconfig.cs and web.config also i am facing the same error.
Please clarify how do i come out of this error,
Replace http://localhost:4200 with "*" from EnableCorsAttribute method.
void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(corsAttr);
}
and remove httpProtocol configuration settings from web.config.

No custom/authorization Headers in MVC 5 controller

I have an MVC 5 ViewController which does not accept headers from an Ajax call. The ajax call origin is a different website then the controller.
The Ajax call looks like:
window.jQuery.ajax({
url: 'http://localhost:54155/TestView',
headers: {'Authorization': 'token'},
cache: false,
contentType: 'application/json; charset=utf-8',
method: 'Get',
dataType: 'json',
data: {}
}).success(alert('succes?'))
.error(alert('failed'))
});
Cors is enabled on the controller side:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
And I'm trying to reach this controller:
public class TestViewController : Controller
{
public ActionResult Index()
{
var keys = Request.Headers.AllKeys;
return View();
}
}
If I send the request to a WebApi based on a WEP API 2 controller, the headers are ok. If I send a request with postman to the mvc controller the headers are ok as well.
The Headers contain the header Access-Control-Request-Headers, which has the value authorization. But Request.Headers["Authorization"] is null.
Custom headers like X-MyHeader turn up as value from Access-Control-Request-Headers, but when used like a key, they are all null.
Which part am I missing?
I had a same kind of issue - but this might resolve your problem
Install Microsoft.AspNet.WebApi.Cors from NuGet - Run this command
(Install-Package Microsoft.AspNet.WebApi.Cors) in your package
manager console - this will install your Cors
Remove your access allow origin code from your Web.config file
If it is Web Api add the below cod in your WebApiConfig.cs if not try to add in your Gloabl.asax
var cors = new EnableCorsAttribute("*", "*", "*", "*");
config.EnableCors(cors);
You will be wondering where that method EnableCors() will come using System.Web.Http.Cors; add this line in your using and see the magic
This might solve your problem - Finally its not a good idea to access your MVC controller from different domain try you use WebApi
If you want to access your MVC controller try out your ajax code form the same domain
Because WebApi is stateless but MVC is kind of session - Thanks happy coding !!

Web API 2 CORS IIS Express Debug and No Access-Control-Allow-Origin header

Empty web.api project, install Microsoft.aspnet.webapi.cors 5.2.3, add
config.EnableCors();
to webapiconfig. make controller and action
public class HomeController : ApiController
{
[EnableCors("*" , "*" , "*")]
public async Task<string> Get()
{
return await Task.FromResult("omg");
}
}
Debug app and Load up fiddler and do a request to http://localhost:61939/api/Home
there are no CORS headers present. web.config contains:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
what am I missing? Why would this not insert an Access-Control-Allow-Origin header in all request to my Get method?
Also the answer of defining CORS in web.config isn't an answer ... At some point I will need to add origin checking and potentially even checking the HTTP Method something like:
if(requestContext.HttpMethod == "POST" && (origin == "https://someplace.com" || origin == "http://localhost"))
What you've done is enough to enable CORS, you can also enable CORS on all the controllers using this code :
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
I'm not sure how you're testing it, but note that only once the request contains the Origin header, it returns the Access-Control-Allow-Origin header in reponse. If you omit the origin header in the request, the response wouldn't contain the Access-Control-Allow-Origin.

web api routes not working with CORS enabled.

I have CORS enabled in my web api application. and i have API controllers with both classic REST Function names like Get() and Get(string id) and a controllers with custom function names e.g.
[HttpGet]
GetSomeThing()
i have routes configured like this
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
with this arrangement i get an error No 'Access-Control-Allow-Origin' header is present when i try to call controller with Classic REST functions.
e.g. /api/Controller
and if i take route with action after route without action , it gives me the same error on controller calls with custom function names.
e.g. /api/Controller/Function
please note that i have
[EnableCorsAttribute("http://localhost:xxxx", "*", "*")]
attribute on both controllers. and these calls are being made from angular application.
kindly advice.
Had the same issue. Fixed it by adding CORS headers directly to web.config. No other changes are needed.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="content-type, accept, SOAPAction, origin" />
</customHeaders>
</httpProtocol>
</system.webServer>
Additionally, if you installed CORS via NuGet and were using a previous version of WebAPI, then you may need to uninstall it. CORS will update certain core WebAPI assemblies that may cause compatibility issues, i.e., routes not working.
And of course, you will probably want to limit the allowed origins by replacing the "*" in the Access-Control-Allow-Origin value with the URL's you want to allow.
I ran into this issue and I found it a nightmare to get cors to work.
The fix for me in the end was to remove all references to cors in my app and add just one line in the WebAPIConfig
public static void Register(HttpConfiguration config)
{
config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE, TOKEN"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "rest/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
I also removed the custom headers from my web.config. Hope this help anyone else facing cors issues.

ExtJs 5 Ajax Request with ASP .NET

Despite my best efforts I am not able to send an Ajax request with Json data to a remote web server. I do not know what other places I can put enable CORS and am running out of ideas.
Azure Website App Settings:
cors:allowOrigins: *
MVC Controller: I had installed the NuGet Cors package
[EnableCors(origins: "*", headers: "*", methods: "*")]
Web.config:
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
ExtJs Ajax Request:
Ext.Ajax.request({
url: app.utilities.url,
defaultHeaders: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization,Content-Length, X-Requested-With'
},
cors: true,
useDefaultXhrHeader: false,
params: {
jsonData: Ext.util.JSON.encode(formData)
}
Yet I still get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at {my url} This can be fixed by moving the resource to the same domain or enabling CORS.
Is there something I am missing?
Would you consider JsonP (JSON with Padding)?
http://docs.sencha.com/extjs/6.0/6.0.0-classic/#!/api/Ext.data.JsonP
Only for the development purpose you can set below parameter in your browser.It works for me.
--disable-web-security --allow-file-access-from-files --allow-file-access

Resources