Cross Domain API in vNext - c#

I am working on vNext, and trying to create a web api in asp.net vNext. following are the sample code that i used to create api
public class UserController : Controller
{
public IActionResult Get()
{
return Result.Json(new { message = "Valid" });
}
}
I can access this api on browser directly and even i can access this api in same domain view by ajax get request, sample code is below
$.ajax({
type: "GET",
// Get the action URL
url: "http://mydomainname/api/user",
dataType: "json",
success: function (data, textStatus, jqXHR) {
alert(data.message);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
But, when i am trying to access this api by means any other domain or jfiddler , it is not working.
check this jfiddler link
http://jsfiddle.net/2r8wj62a/14/
I am using VS2014 CPT.
an i missing anything... any help will appreciated.
Thanks in Advance...!

beta.smallshiptravel.com resolves to ip 74.114.167.68 on my end. Is it the same on your end?
I've tried the link and it is returning:
HTTP/1.1 404 Not Found
Content-Type: text/html
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
So it looks like you are running inside iis and iis returns not found. I would check the iis logs if the request are actually ending up inside your iis server, or if another server (or reverse proxy) is returning the calls. It it does end up in your server then I would add some logging in my code to every request so i could see it my code actually gets called.
HTH,
Bart

Related

HTTP Error 405 When Using HTTP Delete Only on Host .Net Core 6

I'm getting a 405 error when trying to Delete from any Controllers. I can do it just fine in VS IDE, but cannot figure out why Not in host (request will sent by ajax)
Header Controller
[Authorize]
[Route("Api/v{version:apiVersion}/Cart")]
[ApiVersion("1.0")]
[ApiController]
public class CartApiController : ControllerBase
Note that: tried with CartApiController : Controller too
Controller
[HttpDelete("{CartId:long}", Name = "DeleteCart")]
public IActionResult DeleteCart(long CartId)
{
if (!_CartRepository.DeleteCart(CartId,Convert.ToInt64(_AccountRepository.GetClaim("ID"))))
return Ok(_ResultContentRepository.GetResultContent(1));
return Ok(_ResultContentRepository.GetResultContent(200));
}
Sender
SendApiAsync("Api/Cart/" + input.id, "delete", null, true, false, false).then(function () {
location.reload();
});
Part of Ajax
$.ajax({
url: Url,
headers: Headers,
type: Type,
async: true,
data: Data,
contentType: "application/json",
dataType: 'json',
success: function (data) {
etc...
}
note that:
this Api Sender Works fine by all Methods except http delete only on host
didn't wrote the complete code for Api sender
if url has a api address, url will be replace with the right path
(it's not a path problem)
I've Asked About this issue with the support team of my website Hosting and they told me it's a security configuration I can't use Http Delete so I Changed Every Http Delete to Http Get Starting With "Delete/" Path

Unable to redirect to external URL in MVC controller

I am trying to integrate atoms payment gateway in my MVC project. I have been getting this nasty error even after enabling CORS. So I thought perhaps it is the return url that is causing the issue. So I wrote a simple redirect to find out real cause return Redirect("https://google.com"); but i am still getting same error. What am I doing wrong?
public ActionResult TransferFund()
{
return Redirect("https://google.com");
}
Failed to load https://google.com/: Response to preflight request doesn't pass
access control check: No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:25850' is therefore not allowed
access. The response had HTTP status code 405.
I have followed This to redirect
EDIT
<script type="text/javascript">
$(document).ready(function () {
$('#btnatom').on('click', function () {
$.ajax({
type: 'POST',
url: "/AtomPayment/TransferFund",
data: {},
dataType: "text",
success: function (resultData) { alert("Save Complete") }
});
});
});
</script>
[HttpPost]
public ActionResult TransferFund()
{
return new RedirectResult("http://google.com");
string strURL, strClientCode, strClientCodeEncoded;
....
}
You could not make redirect in 'TransferFund' method, becuase of 'POST' method. Do it from jquery. Here corrected code:
<script type="text/javascript">
$(document).ready(function () {
$('#btnatom').on('click', function () {
$.ajax({
type: 'POST',
url: "/AtomPayment/TransferFund",
data: {},
dataType: "text",
success: function (resultData) {
if(resultData == "Ok"){
alert("Save Complete");
window.location = "https://google.com/"
}
}
});
});
});
</script>
[HttpPost]
public ActionResult TransferFund()
{
//do some transfer work
return Content("Ok");
}
let's drill down into the error:
Failed to load https://google.com/: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin
'http://localhost:25850' is therefore not allowed access. The
response had HTTP status code 405.
you are hitting a Cross Domain request issue.
Google is denying you, for security reasons from reaching it's server. It doesn't matter if you issue POST or GET request, google doesn't recognize your domain and blocks your cross-domain request.
If you use jquery it will work, yes, because you make a request from client-to-client using the window.location property of java script.
if you want to RedirectResult from your controller code, you need to use address at your local domain that will accept the request and won't deny it.
you can read more here about Error 405.
what it means, is:
The administrator can configure each web server so that the individual
methods are either allowed or not allowed. For example, if there’s no
interactive content on the website, it’s only logical that the POST
method isn’t allowed, since the user has no options to enter their own
data and send it to the server. Otherwise, the error message mentioned
above with the status code 405 would appear, informing the browser and
its user that the method is not allowed.
Just Incase anyone needs:
First redirect your other "http://example.com" to another controller ("RedirectController") without httpMethod
[HttpPost]
public IActionResult TransferFund(){
Return Redirect("redirect?url=http://example.com");
}
Now in:
RedirectController.cs
RedirectController(){
public IActionResult Indext(){
var url = Request.Query["url"];
Return Redirect(url);
}
}
or we can redirect to current controller btw

ASP.Net MVC 5 SPA Template OWin /token results in 'invalid_client'

In AngularJS and using Chrome Advanced REST Client I am trying to get the token using the 'password' grant_type from an ASP.Net MVC 5 SPA Visual Studio 2015 Template based project. The project is brand new with no modifications at all.
The endpoint is called using this URL:
http://localhost:55472/Token
[Headers]
Content-Type: application/x-www-form-urlencoded
Accept: application/json
[Encoded Payload]
Data:=grant_type%3Dpassword%26username%3Db%40c.d%26password%3DPass123--%26client_id%3Dweb
And the result is this:
400 Bad Request
{"error":"invalid_client"}
No external login is configured and the user registered using the template application.
I tried different ways to construct the payload like this and got the same result:
[Encoded Payload]
grant_type=password&username=b%40c.d&password=Pass123--&client_id=web
So out of this, it might be the client is not calling the endpoint properly:
var _tokenPath = '/Token';
var data = 'grant_type=password&username=b#c.d&password=Pass123--&client_id=web;
$http.post(_tokenPath, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(
function (response) {
debugger;
console.log(response);
},
function (error) {
debugger;
console.log(error);
}
)
Or there's something not right in the Startup.Auth.cs file which prevents the endpoint from working properly.
How do we get the /Token url working out of the box on the SPA Template for MVC5?
Thanks for your help!
It seems that you are using katana.
This is technically an obsolete technology and has been superseded by asp.net-5.
I would recommend installing it from http://get.asp.net and trying it from there.

server call from client not working

I have a small angularjs application where I'm trying to call a server side function.
I'm not sure but I feel kind a lost when it comes to use the right url for GET/POST from client to server...But I'm not sure the problem is there..
My angular:
$http.get({
method: 'GET',
url: '/Models/Person/GetTestPersons'
}).then(function successCallback(response) {
alert(response);
}, function errorCallback(response) {
alert("ErrorCallback");
});
My server function (Models/Person.cs):
public static string[] GetTestPersons()
{
return new[]
{
"Person1",
"Person2"
};
}
Now I get to the "alert("ErrorCallback")"
And if I could get this to work.. How do I read the array that is returned?
Error:
GET http://localhost:51203/Views/[object%20Object] 404 (Not Found)
You ought to create a Web API project,
The controller will orchestrate call to your Person model.
A quick starter tutorial is here
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

JSONP no get value result

I'm doing a project for college where one WebSite sends commands to a Windows Forms application. This application is responsible for access to serial port and send and receive commands.
Communication between the Website and the Windows Forms application, I used Web Api, however after publishing, auditioning remembered that the localhost in a C # WebSite. Net's own site and not my Windows Forms application.
I changed the call to the Web Api directly use Ajax and not a controller.
In the examples I found I saw that I use JSONP, but I can not read the results and use it on my website.
The calling code and return seen by Chrome are below
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
jsonpCallback: "cmdTorre",
jsonp: "cmdTorre"
});
}
function cmdTorre(data) {
alert(data);
}
Response Header
Content-Length:10
Content-Type:application/json; charset=utf-8
Date:Tue, 10 Jun 2014 11:18:30 GMT
Server:Microsoft-HTTPAPI/2.0
Response
No Properties
Windows Forms APIController
namespace TCCWindows.Lib
{
public class GPSController : ApiController
{
[HttpGet]
public string Posicao()
{
var coordenada = TCCWindows.FormPrincipal.PegarCoordenadas();
return coordenada.Latitude + "|" + coordenada.Longitude + "|" + coordenada.Altitude;
}
}
}
First, you ajax call looks overly complicated try replacing it with :
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
success: cmdTorre,
error: function(err){
alert("You have a error"+err);
}
});
}
function cmdTorre(data) {
alert(data);
}
Please validate the new code carefully. I just typed it in here so can have errors. If this runs at this point you should probably see the error message. That is because your GPSController doesnt seem to be returning a valid JSONP (or JSON for that matter). Please read up on JSONP for more clarification but, I think if you modify your return statement to make it look like following, it should work. Assuming your controller is actually getting called and your network stuff is working:
return "cmdTorre({\"lat\":"+coordenada.Latitude+" , \"lon\":"+coordenada.Longitude+" });"
Basically your return string should look like following when printed on console:
function cmdTorre({
"lat": 23.34,
"lon":34.23,
"alt":50
});
Again I suggest you check the code I wrote for syntax issues as i just typed it up in here, but it should give you the idea.
So problems were:
The return string you are generating is NOT in JSON format
It is also not wrapped in a function call making it a invalid JSONP too.
Lastly my solution should get your code working and JSONP started but its not the right way to do things. Its more of a ugly hack. Your GPS controller should read the HTTP request for parameter called 'callback' which is a accepted convention for JSONP calls. Then instead of hardcoding the function name in the return statement, you should use the value of this callback parameter. Then you dont need to use a specific function like 'cmdTorre' in your jQuery. Instead a anonymus function like success:function(response){...} will work just fine.
Hope that helps.

Categories